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

1

2 Answers 2

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));
  }
...
Sign up to request clarification or add additional context in comments.

Comments

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
      )                
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.