Angular 从POST调用中提取错误状态/消息

Angular 从POST调用中提取错误状态/消息,angular,observable,Angular,Observable,我有一个来自angular服务的rest api的POST调用,我想返回错误状态或错误消息来对其进行一些逻辑处理,但总是得到[Object]作为响应(或未定义,取决于我从错误处理方法返回的内容),我无法解析它 从我的服务: addDbResource(resource) { //console.log(JSON.stringify(resource)); this.http.post(this.url + "resource", JSON.stringify(resource),

我有一个来自angular服务的rest api的POST调用,我想返回错误状态或错误消息来对其进行一些逻辑处理,但总是得到[Object]作为响应(或未定义,取决于我从错误处理方法返回的内容),我无法解析它

从我的服务:

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

您是否尝试在http post调用中添加
{observe:'response'}
属性

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

它将为您提供一个完整的Http响应对象,其中包含头和响应状态。这就是我在最后解决它的方法:

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);
        });*/

}  
我意识到我不能保存我想要的数据从订阅内部,然后从外部使用它。
逻辑必须在subscribe中。

我不能将其作为pf参数的一部分传递!getting:类型为“{observe:string;}”的参数不能分配给类型为“RequestOptionsArgs”的参数。Object literal只能指定已知的属性,并且类型“RequestOptionsArgs”中不存在“observe”。我还试着像这样将其添加到options对象中:this.headers=newheaders({'Content-Type':'application/json','Accept':'application/json'});this.options=newrequestoptions({headers:this.headers,observe:'response'});但是也不起作用我不明白为什么当我在全局变量中保存消息或状态时,错误处理方法没有返回到调用方法?!没有定义!但是当从error方法内部将其打印到(console.log)时,它就在那里。
response.subscribe(res => {
        if (res.status == 200) window.location.href = "app/components/resourses-list";
        });