我写了一个HttpInterceptor,我想在其中使用NotificationService。但是httpInterceptor中的NotificationService未定义。有没有错过。
HttpInterceptor.ts
...<imports>...
export class HttpInterceptor extends Http {
constructor(
backend: ConnectionBackend,
defaultOptions: RequestOptions,
private notificationService: NotificationService
) {
super(backend, defaultOptions);
}
private beforeRequest(): void {
this.notificationService.showPreloader(); //this.notificationService is undefined
}
get(url: string, options?: RequestOptionsArgs): Observable<any> {
this.beforeRequest();
return super.get(HttpInterceptor.getFullUrl(url), HttpInterceptor.requestOptions(options))
}
}
NotificationService.ts
export class NotificationService {
showPreloader() {
console.log('preloader show!');
}
}
AppModule.ts
providers: [ModalModule, NotificationService, {
provide: HttpInterceptor,
useFactory: httpFactory,
deps: [XHRBackend, RequestOptions]
}],
export function httpFactory(backend: XHRBackend, defaultOptions: RequestOptions, notificationService: NotificationService) {
return new HttpInterceptor(backend, defaultOptions, notificationService);
}
答案 0 :(得分:4)
你错过了工厂的一个依赖:
deps: [XHRBackend, RequestOptions, NotificationService]
^^^^^^^^^^^^^^^^^^
add this