Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 empty response handling

Tags:

angular

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.

like image 356
Starfish Avatar asked Aug 15 '16 07:08

Starfish


1 Answers

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

 if (res) {
       return res.json() || {};
     }
like image 168
nacho_dh Avatar answered Sep 24 '22 23:09

nacho_dh