0

i have this service that is an http get request that response with a list of products:

import 'rxjs/Rx';
import {Injectable} from '@angular/core';
import {Http} from '@angular/http';

  @Injectable()
    export class ProductService{
      constructor(private _http:Http) {}

      getData() {

          return this._http.get(`URL GOES HERE`)
            .map(res => res.json());

      }
    }

and this component call the service:

import { Component, OnInit }  from '@angular/core';
import { ProductService } from './product.service';
 class ProductListComponent implements OnInit {
    constructor(public _productService: ProductService) {}

 ngOnInit() {
    this._productService.getData()
      .subscribe(data => this.products = data,
               err => console.log(err));
  }
}

I want to manage the .error; when the service goes in error, i want to refresh the service:

this._productService.getData()
          .subscribe(data => this.products = data,
                   err => { **recall this._productService.getData()** }

Thank for all responses

Alex
  • 111
  • 1
  • 13
  • Does this answer your question? [RxJS - observable doesn't complete when an error occurs](https://stackoverflow.com/questions/33783967/rxjs-observable-doesnt-complete-when-an-error-occurs) – Davy Dec 03 '19 at 10:47

2 Answers2

2

you can use retry operator from rxjs/operators, just specify how many times you want to retry as an argument retry(x_times):

...
ngOnInit() {
    this._productService.getData().pipe(retry(1))
      .subscribe(data => this.products = data,
               err => console.log(err));
  }
...
Bilel-Zheni
  • 1,202
  • 1
  • 6
  • 10
2

You can use retryWhen operator instead of retry to avoid rapid succession of http calls, and you can retry the call just in case of 503 error (Service Unavailable)

.pipe( retryWhen(error => {
       return error.pipe(
        flatMap((error: any) => {
             if(error.status  === 503) {
               return Observable.of(error.status).delay(1000)
             }
             return Observable.throw({error: ''});
          }),
          take(3) // controls number of retries
      )                
});
Fateh Mohamed
  • 20,445
  • 5
  • 43
  • 52