在组件上注入http拦截器

Joã*_*ulo 3 angular-http-interceptors angular

我创建了这个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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的组件中,我做到了:

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

}
Run Code Online (Sandbox Code Playgroud)

在app.module,我提供了这样的拦截器:

providers: [
   {
        provide: HTTP_INTERCEPTORS,
        useClass: NoopInterceptor,
        multi: true
    }
]
Run Code Online (Sandbox Code Playgroud)

当我按照上述方式进行操作时,会得到No provider for NoopInterceptor!,因为我没有提供NoopInterceptor,但是如果我提供NoopInterceptor这样的内容:

providers: [
   {
        provide: HTTP_INTERCEPTORS,
        useClass: NoopInterceptor,
        multi: true
    },
    NoopInterceptor
]
Run Code Online (Sandbox Code Playgroud)

我将进行两次注入,而组件将得到错误的注入,那么我将无法订阅statusChange。我该如何解决?

小智 6

您是否尝试在 HTTP_INTERCEPTOR 和 useExisting 而不是 useClass 的提供之前放置 NoopInterceptor ?这样你应该只得到一个 NoopInterceptor 实例。


Est*_*ask 6

可能使用以下方法创建单个拦截器实例:

providers: [
    NoopInterceptor,
   {
        provide: HTTP_INTERCEPTORS,
        useExisting: NoopInterceptor,
        multi: true
    }
]
Run Code Online (Sandbox Code Playgroud)

但是加载指示符状态的一种正确解决方案(我想statusChange是为了这个目的)是将其与拦截器分离并使其成为单独的提供程序。

就像这里显示的那样,应该有请求计数器,因为可以有并发的请求,并且应该同时受到成功和错误do回调的影响。