Angular 4 : get error message in subscribe

2020-05-19 05:37发布

问题:

In the service, there is this code :

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

In the component :

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

When it's the 'customer' exist, no problem I get all the information about the customer.

When the id does not exist, the web api return 'BadRequest' with a message. How can I get this message ? the status ?

Thanks,

回答1:

(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);
}


回答2:

Sometimes when you call catch without using arrow function like below

getUserList() {
    return this.http.get(this.constURL + '/loans/all', this.headerOptions)
    .catch(this.handleError);
}

handleError(error: Response) {
    if (error.status == 500) {      
      this.router.navigate(['/login']);
    } else {
      return Observable.throw(error);
    }
}

then it gives error of

ERROR TypeError: Cannot read property 'navigate' of undefined not getting this

Because in handleError function this object is not accessible..if you console this.router then you will get undefined.. so this object not working and not getting router all available methods

So you have to use arrow function here like below

getUserList() {
    return this.http.get(this.constURL + '/loans/all', this.headerOptions)
    .catch(error => { 
      return this.handleError(error);
    });
}

handleError(error: Response) {
    if (error.status == 500) {      
      this.router.navigate(['/login']);
    } else {
      return Observable.throw(error);
    }
}

Also if you have not mentioned return for handlerError function then it will throw error again like

Argument of type '(error: any) => void' is not assignable to parameter of type

So its necessary to type return for handlerError function.

Check in details here . He has explained code very well with all possible errors and solution of that..worked for me