【问题标题】:Cancel /Kill http api call angular 2取消 /Kill http api 调用 angular 2
【发布时间】:2017-06-02 20:12:17
【问题描述】:

有时http api 调用需要很长时间才能加载数据。在这种情况下,如果我们移动另一个组件,它仍然会继续执行(我们可以在浏览器控制台中看到它)。那么,当我们移动到另一个组件时,有什么方法可以取消或终止 http api 调用?

【问题讨论】:

    标签: api http angular angular2-services angular2-http


    【解决方案1】:

    您可以通过在OnDestroy 生命周期事件中使用unsubscribe() 方法“杀死”它,假设您正在使用订阅,例如:

    mySubscription: any;
    
    ngOnInit() {
        this.mySubscription = this.myHttpCall().subscribe...
    }
    
    ngOnDestroy() {
        this.mySubscription.unsubscribe();
    }
    

    【讨论】:

    • 谢谢... :) 通过使用它,我可以unsubscribe() 一个 api,但是有什么方法可以让我只使用一个变量就可以unsubscribe() 多个 api。
    • 您可以使用 rxjs 中的 takeWhile() 函数取消订阅所有订阅:示例:brianflove.com/2016/12/11/anguar-2-unsubscribe-observables
    【解决方案2】:

    您可以使用 rxjs 中的 takeWhile() 函数取消订阅所有订阅:示例:

    http://brianflove.com/2016/12/11/anguar-2-unsubscribe-observables/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2017-01-02
      • 1970-01-01
      • 2017-03-29
      相关资源
      最近更新 更多