我该如何设置此HttpInterceptor
? oidcSecurityService
未定义。
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
}
]
答案 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日