Angular2 empty response processing

In my current application, I cannot get a response from an observable when it is empty, or when the server takes too long to respond. Here is my current state:

getIncomingData():Observable<any[]> { console.log("GetIncomingData"); return this.http.get('http://mylink/data') .map(data => this.extractIncomingData(data)) .catch(this.handleError); } private extractIncomingData(res:Response):any[] { if (res.status < 200 || res.status >= 300) { throw new Error('Bad respons status: ' + res.status); } console.log(res.json()); return <any>res.json(); } 

I tried to use .timeout , which I found somewhere else, but it does not work. I am using Angular2 rc1. Does anyone know how to solve my problem? Thanks.

+6
source share
2 answers

You can use the following if statement to safely retrieve data.

  if (res) { return res.json() || {}; } 
+1
source

nacho_dh's answer was close, but res is an object that is unlikely to be null. In the case where I had this problem, the res object was a valid object, but the _body property was', this is what causes res.json () to throw an exception. Therefore you need to:

 .map(res => (<any>res)._body == '' ? {} : res.json()) 

Please note that when working with Angular 2 and therefore Typescript you need to send res to <any> because _body is private and Typescript will not allow you to access it.

yes i know its hacked, thanks

0
source

All Articles