Angular 4 HttpInterceptor:显示和隐藏加载程序

Angular 4 HttpInterceptor:显示和隐藏加载程序,angular,httpclient,interceptor,loader,Angular,Httpclient,Interceptor,Loader,我已经实现了接口,以便拦截传出的请求和传入的响应 我想在创建请求时显示加载程序,在收到响应时隐藏该加载程序 虽然下面的代码在检测到HttpResponse时起作用,但它没有检测到Http故障(当响应代码不同于200时),因此加载程序不会被隐藏 @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor(private loaderService: LoaderService) { } i

我已经实现了接口,以便拦截传出的请求和传入的响应

我想在创建请求时显示加载程序,在收到响应时隐藏该加载程序

虽然下面的代码在检测到HttpResponse时起作用,但它没有检测到Http故障(当响应代码不同于200时),因此加载程序不会被隐藏

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private loaderService: LoaderService) { }

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    this.loaderService.show();

    return next
        .handle(req)
        .do(event => {
            //nothing is printed when a Http failure occurs
            console.log('detecting event ', event);
            if (event instanceof HttpResponse) {
                console.log('detecting http response');
                this.loaderService.hide();
            }
        });
  }
}
@Injectable()
导出类AuthInterceptor实现HttpInterceptor{
构造函数(私有loaderService:loaderService){}
截取(req:HttpRequest,next:HttpHandler):可观察{
this.loaderService.show();
下一个返回
.句柄(req)
.do(事件=>{
//发生Http故障时不会打印任何内容
console.log('检测事件',事件);
if(HttpResponse的事件实例){
log(“检测http响应”);
this.loaderService.hide();
}
});
}
}

尝试将带有catch的错误处理添加到可观察的下一个:

.catch((error: any) => {
        if (error instanceof HttpErrorResponse) {
          this.loaderService.hide();
          // show the error to the user here
        } else {
          return Observable.throw(error);
        }
 })

我建议只需添加一个finally操作符,它可以在成功和错误情况下完成这项工作:

import 'rxjs/add/operator/finally';

// ...

.finally(()=> this.loaderService.hide())

由.do方法创建的Observable对源发出的每个值、错误和完成执行副作用。实际上,当它看到某些事情发生时,它会窥探原始的可观察对象并触发这些副作用

请参阅文档

您可以通过添加错误处理程序来执行自己的操作,就像您已经为示例中的值执行的操作一样:

return next
    .handle(req)
    .do(event => {
        //nothing is printed when a Http failure occurs
        console.log('detecting event ', event);
        if (event instanceof HttpResponse) {
            console.log('detecting http response');
            this.loaderService.hide();
        }
    }, (err: any) => {
        console.log('... error occurred');
        this.loaderService.hide();
    });

还有可能在这种情况下使用的补全副作用。

我认为您需要检查一下这一点,或者从中汲取灵感。如果我们调整代码,使其返回一个可观察的结果,无论如何,它都会起作用。谢谢你的帮助