It seems a bit complicated, so I suggest simplifying it like this:
public setUser(): void {
this.api.get<any>(environment.apiUserRoot + `/Users/current`).subscribe({
next: (userData) => {
this.storage.clearIdentity();
this.assignLoginUserToUser(userData.body);
},
error: (err) => {
this.storage.clearIdentity();
},
});
}
If you need a return value, there are different options based on the rxjs version you are using:
public setUser(): Promise<any> {
return this.api.get<any>(environment.apiUserRoot + `/Users/current`)
.toPromise().then(userData => {
this.storage.clearIdentity();
this.assignLoginUserToUser(userData.body);
return userData;
}).catch(() => {
this.storage.clearIdentity();
});
}
- If you have
firstValueFrom
, you can do it like this:
public setUser(): Promise<any> {
return firstValueFrom(this.api.get<any>(environment.apiUserRoot + `/Users/current`))
.then(userData => {
this.storage.clearIdentity();
this.assignLoginUserToUser(userData.body);
return userData;
}).catch(() => {
this.storage.clearIdentity();
});
}
For obtaining the user, you have several options depending on your async implementation choice (observable or promise; observables are recommended):
- With observables, the
setUser
method should not subscribe itself but handle side effects with tap
and return the observable for later use.
public setUser(): Observable<UserModel> {
return this.api.get<any>(environment.apiUserRoot + `/Users/current`).pipe(
tap(result => {
this.storage.clearIdentity();
this.assignLoginUserToUser(result.body);
return result.body;
}),
catchError(err => {
this.storage.clearIdentity();
return of(null);
})
);
}
The getUserContext
method should now return an Observable instead of being synchronous:
public getUserContext(): Observable<UserModel> {
return this.setUser();
}
This means that the calling code needs to subscribe to the observable returned by getUserContext
like this:
getUserContext().subscribe(user => {
// process user data here.
});
- With promises, you should return the promise obtained from the
setUser
method using one of the implementations mentioned above (with .toPromise
or firstValueFrom
)
public getUserContext(): Promise<UserModel> {
return this.setUser().then(result => result.body);
}
The calling code also needs adjustments to handle the fact that getUserContext
is no longer synchronous:
const user = await getUserContext();
or use then
getUserContext().then(user => {
// process user data here.
});