Search code examples
androidiosangularionic2angular2-http

angular2 http.post to a turned off server => return error on Android BUT NOT ON IOS


I am using Angular 2, Ionic 2.

I shut down the server my app sends its request to, in order to check how the offline mode is managed.

I have made a Custom HTTP Service for my project based on import { Http, Headers, Response, RequestOptions, RequestMethod, Request } from '@angular/http'. It includes a 'function sendRequest':

public sendRequest = (data):Observable<Response> => {
    // console.log("CustomHttpService->sendRequest() starts");
    let headersToUse = new Headers();
    headersToUse.append("Content-type",'application/x-www-form-urlencoded');
    data = this.jsonToURLEncoded(data);
    let options = { headers:headersToUse };
    return this.http.post(this.url, data, options).map(
    (res:Response)=>{
        return res.json();
    }
    ).catch(
            this.handleErrorObservable
        );
  }

And the 'function handleErrorObservable':

private handleErrorObsevable (error:Response|any){
    console.log("handleError error.message " + error.message);
    console.log("handleError error " + error);
    return Observable.throw(error.message || error);
}

In Android it works, after a certain time I get in the log:

handleError error Response with status 0 for URL: null

But on IOS the error never arrives, like if there was no time out set. Any tips?


Solution

  • I solved it by adding a custom timeout setting on the observable like in that SO question, in my function. It looks like that now:

    public sendRequest = (data):Observable<Response> | Observable<any> => {
    // console.log("CustomHttpService->sendRequest() starts");
    
        let headersToUse = new Headers();
        headersToUse.append("Content-type",'application/x-www-form-urlencoded');
    
        data = this.jsonToURLEncoded(data);
    
        let options = { headers:headersToUse };
    
        return this.http.post(this.url, data, options).timeoutWith(CustomHttpService.TIMEOUT_DELAY,Observable.throw(new Error(CustomHttpService.ERROR_REQ_HTTP))).map(
            (res:Response)=>{
                return res.json();
            }
        )
        .catch(this.handleErrorObservable)
    }
    
    private handleErrorObservable (error:Response|any){
        console.error(CustomHttpService.CLASS_TAG + " handlerErrorObservable: error.message " + error.message);
    
        return Observable.throw(error.message);
    
    }
    

    Also it requires to add on the top of the class some specific import to use the functions timeoutWith and Observable.throw: import 'rxjs/add/operator/timeoutWith and import 'rxjs/add/observable/throw like it is explained in the official Angular2 doc.