取消http请求

Cancel http request

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

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

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

xhr.abort();

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

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

当你订阅时,你会得到一个订阅,你可以用它来取消订阅

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

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

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