Angular 4 : get error message in subscribe

前端 未结 2 1007
没有蜡笔的小新
没有蜡笔的小新 2021-02-01 03:03

In the service, there is this code :

  getUser(id){
    return this.http.get(\'http:..../\' + id)
      .map(res => res.json());
  }

In the

2条回答
  •  孤城傲影
    2021-02-01 04:00

    (err) needs to be outside the customer fat arrow:

    this.myService.getUser(this.id).subscribe((customer) => {
      console.log(customer);
      this.customer = customer,
    },
    (err) => {console.log(err)});
    

    To get the error msg back, add a catch that will return the error object:

    getUser(id){
      return this.http.get('http:..../' + id)
        .map(res => res.json())
        .catch(this.handleError);
    }
    
    private handleError(error: any) { 
      let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
      return Observable.throw(error);
    }
    

提交回复
热议问题