Angular 4: get a subscription error message

The service has this code:

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

In component:

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

When the "client" exists, there is no problem, I get all the information about the client.

When the identifier does not exist, the web api returns a "BadRequest" with a message. How can I get this message? status?

Thanks,

+5
source share
2 answers

(err) must be outside the customer arrow:

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

To return an error message, add a catch that will return an 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); } 
+7
source

Sometimes, when you call catch without using the arrow function, as shown 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 he gives an error

ERROR TypeError: Cannot read the 'navigate' property from undefined without receiving this

Because in the handleError function, this object is not available. If you are the this.router console, then you will get undefined .. therefore this object does not work and does not receive the router of all available methods.

So you should use the arrow function here as shown 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); } } 

In addition, if you did not mention return for the handlerError function, then it throws an error again, for example

An argument of type '(error: any) => void' is not assigned to a type parameter

Therefore, you must enter return for the handlerError function.

Read more about registration here . He very well explained the code with all possible errors and a solution to this. Worked for me.

0
source

Source: https://habr.com/ru/post/1270035/


All Articles