1
votes

I have a POST call to rest api from my angular service, and I want to return either the error status or the error message to do some logic on it, but am always getting [Object] as response (or undefined, depends on what I return from my error handling method) and I'm not managing to parse it!

From my service:

addDbResource(resource) {
   //console.log(JSON.stringify(resource));

    this.http.post(this.url + "resource", JSON.stringify(resource), this.options)
        //.map(this.extractData)
        .map(res => this.errorStatus = res)
        .catch(this.handleObservableError)
        .subscribe();

   return this.errorStatus;
}  


private handleObservableError (error: Response | any) {
    //console.error("Error1: " + error.message || error);
    let errMsg = (error.message) ? error.message :
        error.status ? error.status + " - " + error.statusText : 'Server error';

    document.getElementById("alert").innerHTML = error.json().message;

    return Observable.throw(error.status);
    //return Observable.throw(error.message || error);
    //return error.status;
}

PSB a screenshot

2

2 Answers

1
votes

Have you tried to add the {observe:'response'} property on your http post call ?

this.http.post(this.url + "resource", JSON.stringify(resource),{observe:'response'})
        //.map(this.extractData)
        .map(res => this.errorStatus = res)
        .catch(this.handleObservableError)
        .subscribe();

It will give you a complete Http response object with headers and the response status

0
votes

This is how I solved it at the end:

addDbResource(resource) {
   //console.log(JSON.stringify(resource));

    return this.http.post(this.url + "resource", JSON.stringify(resource), this.options)
        .catch(this.handleObservableError);
        //.subscribe();

   //More flexible approach
   /*return this.http.post(this.url + "resource", JSON.stringify(resource), this.options)
       .subscribe(response => {
            if (response.ok) { // <== CHECK Response status
                //this.data = response.json();
            } else {
                // handle bad request
            }
        },
        error => {
            this.errorMessage = <any>error;
            document.getElementById("alert").innerHTML = error.json().message;
            console.log("-> " + error.status + " : " + this.errorMessage);
        });*/

}  

and from the component that is calling the addResource method:

response.subscribe(res => {
        if (res.status == 200) window.location.href = "app/components/resourses-list";
        });

I realized that I cant save the data that I want from inside the subscribe and use it from outside after that. The logic has to be inside the subscribe.