Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 rxjs observable forkjoin

Is it possible to continue forkjoin http.get requests even if one of the requests fails.

I'm looking to a similar function of $q.allSettled in angular2.

See example : http://jsfiddle.net/Zenuka/pHEf9/

angular.module('qAllSettled', []).config(function($provide) {
  $provide.decorator('$q', function($delegate) {
    var $q = $delegate;
    $q.allSettled = function(promises) {
      return $q.all(promises.map(function(promise) {
        return promise.then(function(value) {
          return { state: 'fulfilled', value: value };
        }, function(reason) {
          return { state: 'rejected', reason: reason };
        });
      }));
    };
    return $q;
  });
});

Kab

like image 678
kabus Avatar asked Jun 27 '16 08:06

kabus


2 Answers

You could leverage the catch operator for each observable to intercept the error and return another observable in such cases.

Here is a sample:

return Observable.forkJoin(
  this.http.get('/some-url')
         .map((res:Response) => res.json())
         .catch(res:Response => Observable.of({}),
  this.http.get('/some-other-url')
         .map((res:Response) => res.json())
         .catch(res:Response => Observable.of({}),
);
like image 140
Thierry Templier Avatar answered Oct 06 '22 00:10

Thierry Templier


Uses Observable.forkJoin() to run multiple concurrent http.get() requests. The entire operation will result in an error state if any single request fails.

 getBooksAndMovies() {
    return Observable.forkJoin(
      this.http.get('/app/books.json').map((res:Response) => res.json()),
      this.http.get('/app/movies.json').map((res:Response) => res.json())
    );

But you could put your additional GET request in the error handler:

getBooksAndMovies() {
    Observable.forkJoin(
        this.http.get('/app/books.json').map((res:Response) => res.json()),
        this.http.get('/app/movies.json').map((res:Response) => res.json())
    ).subscribe(
      data => {
        this.books = data[0]
        this.movies = data[1]
      },
      err => console.error(err)
    );
like image 22
null canvas Avatar answered Oct 05 '22 23:10

null canvas