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

时间:2019-10-10 23:51:29

标签: angular typescript

我该如何设置此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);
    }
}

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

  providers: [
    OidcSecurityService,
    OidcConfigService,
    {
      provide: APP_INITIALIZER,
      useFactory: loadConfig,
      deps: [OidcConfigService],
      multi: true
    },   
    AuthorizationGuard,
    {
      provide: HTTP_INTERCEPTORS, 
      useClass: AuthInterceptor, 
      multi: true
    }    
  ]

2 个答案:

答案 0 :(得分:2)

试试这个-

@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);
                }
            }
        }

答案 1 :(得分:0)

您可以直接在构造函数中注入服务:

   constructor(private oidcSecurityService : OidcSecurityService) { }

关于在构造函数中注入服务的错误,但已在以下地方修复:

  

Angular 5.2.3发布于2018年1月31日

请检查以下答案: https://stackoverflow.com/a/48903734/3018671