如何在子模块服务中使用Angular拦截器我的应用程序中有6个模块。
所有模块都有自己的服务。我仅在根模块(app.module)中进行了配置,我认为我们需要在所有需要使用拦截器的子模块中进行配置。
我已经创建了拦截器
export class UskHttpInterceptor implements HttpInterceptor { constructor(private router: Router) { } intercept(req: HttpRequest<any>, next: HttpHandler) { const newRequest = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + sessionStorage.token) }); return next.handle(newRequest) } }
应用程序模块
providers: [ { provide: HTTP_INTERCEPTORS, useClass: UskHttpInterceptor, multi: true }, ],
但是当我从服务中调用API时>
getStudents(tenantId, status, studentId) { this.authService.setHttpRequestProcessing(true); return this.http .get(`${this.SERVER_HOST}Student/Tenant/${tenantId}/${status}/${studentId}`, this.getHTTPHeaders()) .pipe( tap( response => { this.authService.setHttpRequestProcessing(false); return response; }, error => { this.authService.setHttpRequestProcessing(false); return error; } ) ); } getHTTPHeaders() { let headers = new Headers(); headers.append('Authorization', 'Bearer ' + sessionStorage.token); // i want to append headers from interceptors headers.set('content-type', 'application/json'); headers.append('accept', 'application/json'); let options = new RequestOptions({ headers: headers }); return options; }
如何在子模块服务中使用Angular拦截器我的应用程序中有6个模块。所有模块都有自己的服务。我仅在根模块(app.module)中进行了配置,我认为我们需要...
不是,您不必,请参考Hierarchical injectors