Retry

There are times when you might want to retry a failed request. For example, if the the user is offline you might want to retry a few times or indefinitely.

Retry example from Slack

Figure: Retry example from Slack

Use the RxJS retry operator. It accepts a retryCount argument. If not provided, it will retry the sequence indefinitely.

Note that the error callback is not invoked during the retry phase. If the request fails it will be retried and only after all the retry attempts fail the stream throws an error.

  1. import { Http } from '@angular/http';
  2. import { Injectable } from '@angular/core';
  3. import { Observable } from 'rxjs/Rx';
  4. @Injectable()
  5. export class SearchService {
  6. constructor(private http: Http) {}
  7. search(term: string) {
  8. let tryCount = 0;
  9. return this.http.get('https://api.spotify.com/v1/dsds?q=' + term + '&type=artist')
  10. .map(response => response.json())
  11. .retry(3);
  12. }
  13. }

View Example

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