Subscribe twice to Angular 2 Http?

I would like to have a service for calling an API that properly processes a request and performs standard error handling on the API requests. For instance I have an ApiErrorsService that I want to call when any API call gets an error. I also want to submit calls in a standard way, i.e. setting the Content-Type to application/json and serializing the request object.

Of course when I subscribe to the observable returned from Http it is called once, and when I return it and the caller subscribes it is called again. What would be the best way to be able to listen for the results in two places without performing the API call twice? Can I just call .publish() or .share() and return that? Do I need to then dispose of it? Are there any timing issues that may occur? If I mock the API call and return a value immediately will that work fine, or will the caller’s subscription miss the values? Here’s the code I have:

post(path: string, data: any): Observable<Response> {
    var headers: Headers = new Headers();
    headers.set("Content-Type", "application/json");
    var s = data == null ? null : JSON.stringify(data, null, 2);
    var shared = this.http.post(path, s, { headers: headers }).share();
    shared.subscribe(null, err => this.appErrorsService.addApiError(err));
    return shared;
}

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

Using share is overkill. if you just want to process the error inline, you can use do instead:

return this.http.post(path, s, { headers: headers })
   .do(null, err => this.appErrorsService.addApiError(err));

Jason
Guest

Using share is enough, http Observable automatically completes, so you don’t have to unsubscribe. There is no way to miss values unless you are going to subscribe second listener in async method (setTimeout/etc).