I am proficient with Angular 1.x/Promises, but totally new to Angular5/Observables. With Angular 1 and Promises, we are able to intercept the HTTP response to an API, do some specific logging with the HTTP response, and then pass back the actual data returned to the caller using a new deferred Promise. The caller then resolves the Promise to get the returned value(s).
I want to do something similar with Angular 5, but I am getting hung up with Observables. I can't seem to figure out how to get the HTTP response, log it or the error, and then propagate the response data back to the caller, with either the data or an error.
EX:
The 'base' function calls the HttpClient 'request' function. I was hoping to subscribe here to do some logging, and then return perhaps a new Observable to pass back, especially if the call succeeds.
base<R>(method: string, url: string) {
const _headers = new HttpHeaders();
const headers = _headers.append(this.CONTENT_TYPE_HEADER, this.CONTENT_TYPE)
.append(this.AUTH_HEADER, (this.AUTH_TYPE + TokenMgrService.UserJwt));
return this.http.request<R>(method, url, { headers: headers, observe: 'response' }).subscribe(
(res: HttpResponse<R>) => {
// Do some detailed logging here...
return res.body;
},
err => {
// Do some error logging here...
return null;
});
}
The 'get' function is a simple wrapper around the 'base' function. The plan is to support other methods (POST, PUT, DELETE) in a similar manner.
get<R>(url: string) {
return this.base('GET', url);
}
The 'getFoo' is an example of the function that would be in an application/API specific service. I would provide the template type and call the 'get' wrapper function.
getFoo(foo_id: number) {
return this.get<Foo>('https://hostname/v1/foos/' + foo_id);
}
I would like the caller to 'getFoo' to be able to subscribe to get the result or error....or do I...am not sure.
// Caller
getFoo(111).subscribe(
res => {
// WAT!?
}
);
The function 'getFoo' is choking because 'subscribe' does not exist on the returned Subscription that originated in the 'base' function.
Obviously, I'm way off base ...can someone point me in the right direction? Thanks.
dooperator. Also, that's what interceptors are for.