Search code examples
angularrxjsobservableangular2-services

GET Request every interval time, with errors handling


I think the question is simple, but I can't repair this code by self.

I have one service doing some GET request. The GET usually returns 200, but some times it's returning 410.

I want to make requests every some interval, for example every second. The problem is when I am using an observable mechanism for this, it fails at first "410", then it returning 410 on console in infinity.

My service code:

getStatistic(){
var headers = new Headers();
headers.append("Content-Type", "application/x-www-form-urlencoded");
var options = new RequestOptions({headers: headers});

return this.http.get('http://localhost:8080/resource',options)
  .retryWhen(errors => errors.delay(5000))
  .map(
  (response:Response) => {
    return response.json();
  }
)
  }



 handleError(error:any){
    if(error.status === 404){
      return Observable.of(false)
    }else if(error.status===410){
      return Observable.throw({code:error.status, msg:error._body})
    }else{
      return Observable.of(false)
    }
  }

And the Observable:

var observable =  TimerObservable.create(5000, 1000)
  .takeWhile(() => true)
  .subscribe(() => {
    this.statisticService.getStatistic()
      .subscribe(
        (data) => {
          console.log("data",data)
        },
        (err) => {
          console.log("err",err)
        }
      );
  },error2 => console.log("error"));

The responses are going like this: 200 200 200 200 410 <- for this moment all responses aren't from requests to server, only cached 410 410 ...


Solution

  • Could it be because

    A 410 response is cacheable by default.

    Client caches that response and doesn't even try to call the server anymore.