Angular 4 HttpInterceptor:显示和隐藏加载器

前端之家收集整理的这篇文章主要介绍了Angular 4 HttpInterceptor:显示和隐藏加载器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经实现了 HttpInterceptor接口,以拦截传出请求和传入响应.

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

虽然代码波纹管在检测到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())

猜你在找的Angularjs相关文章