'Angular2 empty response handling

In my current application I can't seem to get a response from the observable when it's an empty array or when it takes too long for the server to reply. 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 have tried using the .timeout I found somewhere else but that doesn't seem to work either. I'm using Angular2 rc1. Does anyone know how to solve my problem? Thanks.



Solution 1:[1]

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

 if (res) {
       return res.json() || {};
     }

Solution 2:[2]

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

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

Note, given your working with Angular 2 and therefore Typescript you'll need to cast res to <any> because _body is private and Typescript won't let you access it.

yes I know its hacky, thanks

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nacho_dh
Solution 2