加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:03:24 所属栏目:安全 来源:网络整理
导读:我已经实现了 HttpInterceptor接口,以拦截传出请求和传入响应. 我想在创建请求时显示加载程序,并在收到响应时隐藏该加载程序. 虽然代码波纹管在检测到HttpResponse时起作用,但它没有检测到Http Failure(当响应代码不同于200时),因此加载器不会被隐藏. @Injec
我已经实现了 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())

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读