【问题标题】:how to track pending HTTP requests in angular 2如何在 Angular 2 中跟踪待处理的 HTTP 请求
【发布时间】:2017-03-06 16:36:28
【问题描述】:

我想要 Angular 2 中的 Angular 1 $http.pendingRequest 的替代品,或者任何像拦截器一样全局跟踪的东西。主要用于在调用时显示加载图标

【问题讨论】:

    标签: angular angular2-http


    【解决方案1】:

    我可能会在 observable 没有返回时保持图标的状态。

    例子:

    export class MyClass {
        private isLoaded = false;
    
        constructor(private myService: MyService){}
    
        ngOnInit(){
            this.myService.myServiceCall().subscribe(data => {
                console.log(data);
                this.isLoaded = true;
            });
        }
    
    }
    

    然后在对话框中使用*ngIf。你也可以考虑使用 Angular 为这样的场景提供的异步管道:

    https://angular.io/docs/ts/latest/api/common/index/AsyncPipe-pipe.html

    【讨论】:

    • 你如何捕捉加载的百分比?
    • 服务器必须发回有关请求状态的有意义的信息。或者,如果您对请求有足够的了解并且它正在被流式传输,那么您可以计算出一个有意义的百分比。大多数 UI 库只会“猜测”并缓慢增加加载条,以提供用户反馈。
    【解决方案2】:

    你可以这样做:

     getItem(itemID:string){
        if(this.pendingRequest){
            this.pendingRequest.unsubscribe();
        }
        this.pendingRequest = this.http.get(`./country-info/${itemID}`).map((res: Response) => res.json()).subscribe(res => this.item = res.item);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      相关资源
      最近更新 更多