【问题标题】:Cancel http request取消http请求
【发布时间】:2016-03-15 17:48:26
【问题描述】:

在 jQuery ajax 中有一种方法可以中止 ajax 查询:

var xhr = $.ajax({ ... });

当用户想要中止操作或导航到单页应用程序中的其他页面时,我可以调用

xhr.abort();

在 angular2-http api 中,我找不到任何中止查询的可能性,因为它使用 rxjs。

有没有办法在 angular2 中中止 ajax 查询?

【问题讨论】:

标签: typescript angular angular2-http


【解决方案1】:

订阅后,您将获得一个订阅,您可以使用它来取消订阅

this.httpSubscription = this.http.get(...).subscribe(...);
...
this.httpSubscription.unsubscribe();

【讨论】:

    【解决方案2】:

    对于一个简单的解决方案,您可以使用以下方法,但您也可以使用 .switchMap rxjs 方法..

    if ( this.subscription ) {
       this.subscription.unsubscribe();
    }
    this.subscription = this.http.get( 'awesomeApi' )
     .subscribe((res)=> {
      // your awesome code..
    })
    

    【讨论】:

    • 如果 API 调用在循环中怎么办 this.http.get( 'awesomeApi' ) .subscribe((res)=> { // 你的代码很棒.. })
    • 跟踪最后一次订阅(api调用).. if(特殊情况){ kill loop and unsubscripte last subscription } 如果您需要帮助,请提供更多代码
    猜你喜欢
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多