无法在 http 拦截器中注入服务

Jas*_*Jay 1 typescript angular

我需要如何设置HttpInterceptoroidcSecurityService没有定义。

HttpClient让你写拦截器。一个常见的用例是拦截任何传出的 HTTP 请求并添加授权标头。请记住,OidcSecurityService通过构造函数注入拦截器会导致循环依赖。为避免这种情况,请改用注射器。

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    private oidcSecurityService: OidcSecurityService;

    constructor(private injector: Injector) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let requestToForward = req;

        if (this.oidcSecurityService === undefined) {
            this.oidcSecurityService = this.injector.get(OidcSecurityService);
        }
        if (this.oidcSecurityService !== undefined) {
            let token = this.oidcSecurityService.getToken();
            if (token !== '') {
                let tokenValue = 'Bearer ' + token;
                requestToForward = req.clone({ setHeaders: { Authorization: tokenValue } });
            }
        } else {
            console.debug('OidcSecurityService undefined: NO auth header!');
        }

        return next.handle(requestToForward);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是在我的 app.module 中。我需要OidcSecurityService注射。

  providers: [
    OidcSecurityService,
    OidcConfigService,
    {
      provide: APP_INITIALIZER,
      useFactory: loadConfig,
      deps: [OidcConfigService],
      multi: true
    },   
    AuthorizationGuard,
    {
      provide: HTTP_INTERCEPTORS, 
      useClass: AuthInterceptor, 
      multi: true
    }    
  ]
Run Code Online (Sandbox Code Playgroud)

Ana*_*han 5

尝试这个-

@Injectable()
            export class AuthInterceptor implements HttpInterceptor {
                private oidcSecurityService: OidcSecurityService;

                constructor(private injector: Injector) { }

                intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
                    let requestToForward = req;
                    this.oidcSecurityService = this.injector.get(OidcSecurityService);
                    let token = this.oidcSecurityService.getToken();
                    if (token !== '') {
                        let tokenValue = 'Bearer ' + token;
                        requestToForward = req.clone({ setHeaders: { Authorization: tokenValue } });
                    }


                    return next.handle(requestToForward);
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)