[Angular] 4.3 HttpClient with Observable in a Service?

187 views
Skip to first unread message

Alec Taylor

unread,
Jul 23, 2017, 1:01:58 AM7/23/17
to Angular and AngularJS discussion
How do I handle errors in the Service, and Subscribe to responses in the Component?

Previously I have setup my Services like so:

post(user: User): Observable<User> {
const options = new RequestOptions({headers: this.headers});
return this.http.post('/api/auth', JSON.stringify(user), options)
.map(response => {
this.accessToken = response.headers.get('x-access-token');
return response.json()
})
.catch(handleError);
}

Which is useful because the calling Component can then easily:

this.authService.post(user).subscribe(user => {
if (!this.authService.isLoggedIn()) {
this.alertsService.alerts.push({msg: JSON.stringify(user), type: 'warning'});
return;
}
this.alertsService.alerts.push({msg: `Logged in with ${this.authService.accessToken}`, type: 'success'});
this.router.navigate(['/contacts']);
}, error => this.alertsService.alerts.push({msg: error, type: 'danger'}));

I want to move to the new HttpClient ASAP, because of your retry features and especially the reintroduction of interceptors from AngularJS. Then my auth pipeline will work with less hacks!

Thanks for all suggestions

Sander Elias

unread,
Jul 24, 2017, 1:57:23 AM7/24/17
to Angular and AngularJS discussion
Hi Alec,

If you want to propagate errors outside of your service, you have to (re)throw them from within your catch handler. If you don't, your server doesn't expose any error's. 
You have to me smart about this. Because, you might want to handle a 'data-not-there' error differently from an 'hey-you-need-to-be-authed' error, while you might just want to do a retry on a network-level error. It's not all black and white here, and you have to handle every situation differently. 

Regards
Sander

Alec Taylor

unread,
Jul 24, 2017, 9:22:37 AM7/24/17
to Angular and AngularJS discussion
So basically I need to wrap a handler for some classes of errors at the Service level, then return it as an Observable so that Subscribers from Components can handle the other class of errors, and how to share information to the user?

Seems like the kind of wrapper Angular should provider out-of-the-box.

Alec Taylor

unread,
Jul 24, 2017, 9:22:58 AM7/24/17
to Angular and AngularJS discussion
(or is this too trivial a function for me to PR?)

Sander Elias

unread,
Jul 24, 2017, 9:32:34 AM7/24/17
to Angular and AngularJS discussion
Hi Alec,

Not trivial, but highly specific to your use-case. and your demands. can even change from endpoint to endpoint. For example, I do not really care about the 'otherUsersOpionionsOnThisProducts' endpoint, as that's not crucial to my program flow. However, I do care about the 'userCommitOrder' endpoint, as that's central to my business. 

Not all data is equally important. 

Regards
Sander
Reply all
Reply to author
Forward
0 new messages