Cancel a Request

Cancelling an HTTP request is a common requirement. For example, you could have a queue of requests where a new request supersedes a pending request and that pending request needs to be cancelled.

To cancel a request we call the unsubscribe function of its subscription.

  1. @Component({ /* ... */ })
  2. export class AppComponent {
  3. /* ... */
  4. search() {
  5. const request = this.searchService.search(this.searchField.value)
  6. .subscribe(
  7. result => { this.result = result.artists.items; },
  8. err => { this.errorMessage = err.message; },
  9. () => { console.log('Completed'); }
  10. );
  11. request.unsubscribe();
  12. }
  13. }

View Example

原文: https://angular-2-training-book.rangle.io/handout/http/catching-rejections/cancel_request.html