Search code examples
angulartypescriptangular2-services

Angular2 - GET 400 disabling my observable.subscribe with interval


I have app where i have function get() which returning me Observable.interval(1000) with http GET.

In app.component I subscribe this Observable and printing on screen some values from GET.

Everythings works fine until the get response returns 400 - the server send 404 from time to time- its normally. But when i recive 400, my subscribe stops working. Screen show only last valuse and stop "refreshing"

Here is some code:

getAct(symbol:string): Observable<Act> {

return Observable
  .interval(1000)
  .flatMap(() => {
    return this.http.get(url)
      .map((res: Response):Act => (res.json()))
      .catch(err =>  {
        return Observable.throw(err); 
      });
  });

}

And here is code which subscribe:

this.actSub = this.actService
  .getAct(this.symbol)
  .subscribe(
    act => {
        console.log("ok");
        this.act = act;            
      }
    },
    err => {console.warn(err);},
    ()=>console.log("Done")
  );

So, if I run my app in console i have this: enter image description here

So the program run fine - 29 get succesfull, but when it recive 400 its stops, and there where no more "ok".

Where is the problem? Is my getAct() wrong, or maybe when i subscribe I code something bad?

Please help, I tried to repair this, but i couldn't.


Solution

  • There are several RxJS operators to handle errors.

    The easiest would be to use retry():

    return this.http.get(url)
      .retry()
      .map(res => res.json());
    

    This is an agressive strategy as it will re-subscribe to the original observable (this.http.get(...)) as soon as a request fails. You could end up hitting the server really hard.

    You might wanna use retryWhen() instead, which will let you introduce a slight delay before retrying, e.g.:

    return this.http.get(url)
      .retryWhen(errors => errors.delay(2000))  // 2-second delay before retrying
      .map(res => res.json());