I know that I cannot give BehaviorSubject
an Observable value, but I need a way to solve this issue. On app initialization I am fetching current user (if exists), and I need to give the BehaviorSubject
that potential value. So my service code looks like this:
private user = new BehaviorSubject<User>(this.getUser());
public user$ = this.user.asObservable();
getUser(): User {
// does obviously not work!
return this.apiService.getUser()
.map(data => {
if(data) {
return data;
}
// do something else
})
}
So is there some magical rxjs operator to solve this issue, or some other possibility?
Thanks in advance!
I would do it like
private user = new BehaviorSubject<User>(null);
public user$ = this.user.asObservable();
constructor() {
this.getUser();
}
getUser(): User {
// does obviously not work!
return this.apiService.getUser()
.subscribe(data => {
if(!!data) {
this.user.next(data); // <<== added
}
// do something else
})
}