From my understanding, when you subscribe to a BehaviorSubject, that subscription is asynchronous. I am trying to get a value from an object within a BehaviorSubject and return that value in a getter. The getter needs to return the type 'number'. How do I approach this?
Below, I have a getter userId, which should return the user Id from an object held in the BehaviorSubject _loggedInUser
export class AuthServiceService {
private _loggedInUser: BehaviorSubject<LoggedInUserData> = new BehaviorSubject(null);
constructor(
private http: HttpClient,
private storage: Storage
) { }
/// This method below!!! --------------
public get userId(): number{
this._loggedInUser.pipe(
take(1),
map(((loggedInUserData: LoggedInUserData) => {
if(loggedInUserData){
return loggedInUserData.user_id
}
return null;
}))
).subscribe((userId: number | null) => {
return userId;
});
}
//// -----------------
public doLogin(loginData: LoginFormData): Observable<any>{
return this.http.post<LoggedInUserData>(`${authURL}/token`, loginData)
.pipe(
catchError(err => {
if(err.status && err.status === 403)
return throwError('The credentials you have entered are invalid or do not exist.');
else
return throwError('There was an issue processing your request.');
}),
tap(respData => {
console.log('LOGGED IN USER DATA: ', respData);
this._loggedInUser.next(respData);
this.storage.set('userData', respData);
})
);
}
public async autoLogin(){
}
public doLogout(){
}
}