我创建了这个http拦截器:
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
public my_status: boolean = true;
private _statusChange: Subject<boolean> = new Subject<boolean>();
public statusChange$ = this._statusChange.asObservable();
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.changeStatus(false);
const my_req = req.clone({
url: API_PATH + req.url
});
return next
.handle(my_req)
.do(event => {
if (event instanceof HttpResponse)
this.changeStatus(true);
});
}
private changeStatus(status: boolean) {
this.my_status = status;
this._statusChange.next(this.my_status);
}
}
在我的组件中,我做到了:
export class AppComponent implements OnInit {
public my_status: boolean;
constructor(private httpInterceptor: NoopInterceptor) {
this.my_status = httpInterceptor.my_status;
httpInterceptor.statusChange$.subscribe(this.changeStatus);
}
changeStatus(status: boolean) {
this.my_status = status;
}
}
在
app.module
,我提供了如下拦截器:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: NoopInterceptor,
multi: true
}
]
当我按上面的方式做时,我得到
No provider for NoopInterceptor!
,因为我没有提供
NoopInterceptor
,但如果我提供
NoopInterceptor无干扰感受器
这样地:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: NoopInterceptor,
multi: true
},
NoopInterceptor
]
我会打两次针,但组件打错了,那么我就不能订阅了
statusChange