Hi have a very simple function that call an endpoint to retrieve my user, I use it in my header to show the connected user but don't want to call the endpoint every time the header is rendered.
So I'm trying something like this:
public getUser(): User {
if (!this.user) {
this.http.get<User>(environment.apiRoot + '/me').subscribe(res => {
this.setUser(res);
return this.user.value;
}, err => {
});
} else {
return this.user.value;
}
}
With the setUser function:
public setUser(u: User): void {
if (!this.user) {
this.user = new BehaviorSubject(u);
} else {
this.user.next(u);
}
}
And the BehaviorSubject: private user: BehaviorSubject<User>;
In my header component I call it like this in the ngOnInit:
this.user = this.appState.getUser();
console.log(this.user);
But the user in the console.log is always undefined, why it doesn't wait for the subscription in the getUser function ?