2016-03-15 262 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最後訂閱}請提供更多的代碼,如果你需要幫助 –