Angular 4 HttpInterceptor : show and hide loader

标签 angular httpclient interceptor loader

我已经实现了 HttpInterceptor接口(interface)以拦截传出请求和传入响应。

我想在创建请求时显示一个加载器,并在收到响应时隐藏该加载器。

虽然下面的代码在检测到 HttpResponse 时有效,但它没有检测到 Http Failure(当响应代码不同于 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();
            }
        });
  }
}

最佳答案

我的建议是简单地添加一个 finally 运算符,它可以在成功和错误情况下完成工作:

import 'rxjs/add/operator/finally';

// ...

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

关于 Angular 4 HttpInterceptor : show and hide loader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45794281/

相关文章:

angular - 如何配置一个在大屏幕和小屏幕上都很好用的 Material cdk 覆盖位置策略?

angular - 销毁和重新加载子组件

java - org.apache.http.ProtocolException : Target host is not specified

java - 具有 CompletableFuture 的 Vertx HTTPClient 阻止回调线程

c# - NHibernate 拦截器在投影上的使用

node.js - Angular 2 中未找到 @types 模块

angular - 如何获取在其外部 "SetTimeout"内部生成的值

java - 如何在httpget中设置用户名/密码

java - 修改/替换拦截器内的 ClientHttpResponse 主体(ClientHttpRequestInterceptor)

javascript - 为什么nestjs拦截器返回未定义?