2016-03-15 205 views
0

在jQuery的AJAX有办法中止AJAX查询:取消HTTP请求

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

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

xhr.abort(); 

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

有没有办法在angular2中取消ajax查询?

+0

[如何在Angular2中取消订阅]可能的副本(http://stackoverflow.com/questions/34442693/how-to-cancel-a-subscription-in-angular2) –

回答

3

在订阅时,你可以使用订阅退订

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

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

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

如果API调用处于循环中this.http.get('awesomeApi') .subscribe((res)=> { //你的真棒代码.. }) – indra257

+0

最后一次订阅(API调用)的轨道..如果(特殊情况){杀死循环和unsubscripte最后订阅}请提供更多的代码,如果你需要帮助 –