如何使用angular2处理状态代码?

时间:2017-08-05 10:16:57

标签: angular http angular2-forms angular2-services

我是角度2的新手,并试图学习它。我正在一个网站上,响应来自后端api,有两种情况。

1 - 成功回复 - 200 - 状态代码

2 - 错误回复 - 400 - 状态代码

以下是我从后端获得的回复。

1)。

{"message":{
       "message":"Permission already exist.",
        "statusCode":400
    }}

2)。

 {
      "message":{
        "message":"Record successfully inserted ",
        "statusCode":200
     }
   }

但是当我得到400状态代码的错误响应时,它在我的组件中调用为成功函数。下面是成功和错误消息的总代码。 如果我的以下响应格式是正确的,那么在错误函数中不调用错误的错误

Service.ts

 create(data): Observable<any> {
    return this.http.post(this.config.STORE_KEY +  '/public/api/role/create/' + this.userDetails.roleid , data)
      .map((response: Response) => response.json())
      // ...errors if any
      .catch((error: any) => {
                if (error.status <= 400 ||  error.status ===500) {
                    return Observable.throw(new Error(error.status));
                }
            });
  }

component.ts

this.roleService.createRole(requestFormat).subscribe(suc => this.roleSuccess(suc),
             err => this.roleEroor(err));

roleSuccess(suc) {
console.log('sucess')
}

roleEroor(error) {
console.log('error')
}[![enter image description here][1]][1]

1 个答案:

答案 0 :(得分:1)

From the looks of it, I think your backend is always returning an HTTP 200 (OK) response, and it simply includes a "statusCode" property in the response body with a different code depending on the situation.

That is definitely a bad practice, as in case of error in should return an HTTP 400 response, not a 200 with some other way of conveying the error in the body. To check if I am right, either inspect the HTTP response from the backed, or try changing your code to this:

create(data): Observable<any> {
    return this.http.post(this.config.STORE_KEY +  '/public/api/role/create/' + this.userDetails.roleid , data)
      .map((response: Response) => response.json())
      .map((response: any) => {
               if (response.message.statusCode >= 300) {
                    return Observable.throw(new Error(response.message.statusCode));
                }
                return response;
       });
 }

Note that if this works as you expect it, it means the backed has a poor implementation. If you created the backed, then I suggest you change it, otherwise get in contact with whoever developed it.