I am currently stuck with a simple problem.
I have a service called UserService
that aims to be an API layer. I would like to call its method getProfile()
in this way:
- If it is the first time that method is called, it will make a request to my API to retrieve the profile, it will be saved to a variable, and then return it in the form of
Observable
to the component that called it. - If that variable has the profile in it already, just return that, in order to avoid unnecessary network overhead.
I have tried different approaches for this but can't get it completely working (I am a newbie on Angular and rxjs).
This is what I have so far.
getProfile()
method from the UserService
:
public getProfile(): Observable<any> {
if (this.profile) {
return Observable.of(this.profile);
} else {
this.http.get(URLS.URL_GET_PROFILE,
{ headers: this.authZeroService.getAuthorizationHeaders() })
.subscribe(res => {
this.profile = res.json().user.profile;
return Observable.of(this.profile);
});
}
}
Then calling it from the profile component:
userService.getProfile().subscribe(profile => {
console.log(profile);
});