使用 angular2 从 rest api 获取响应错误

get response error from rest api using angular2

Client.service.ts:

add(client: Client): Observable<Client> {
    return this.authHttp.post(this.URI, client)
      .map((res) => res.json()
      //...errors if any
      ,(message)=>message.json());

Client.add.componement.ts:

  this.clientService.add(client)
    .subscribe(_client => {
      this.onAdd.emit(_client);
    },
      message => console.log("THIS ERROR"+message));

但错误的结果是:the result is always bad request

如何获取消息或错误列表the result i get in brower

如果将 angular2-jwt 用作 authHttp,请确保导入它并在服务中正确注入:

import { AuthHttp } from 'angular2-jwt'; -> constructor (private authHttp: AuthHttp) { }

然后,您可以执行以下操作(确保向 POST 请求添加 content-type/request 选项):

add(client: Client): Observable<Client> {
    let headers = new Headers({ 'Content-Type': 'application/json' }); // set content-type
    let options = new RequestOptions({ headers: headers }); // create a request option

    return this.authHttp.post(this.URI, client, options)
        .map((res) => res.json())
        //...errors if any
        .catch(this.handleErrorObservable);
}

private handleErrorObservable(error: Response | any) {
    console.error(error.message || error);
    return Observable.throw(error.message || error);
}

然后当你调用它时:

this._clientService.add(client)
    .subscribe(
         res => console.log(res),
         err => console.log(err)
     );

否则请确保您在网络 api 代码中以 JSON 格式返回所需的回复。