Reputation: 355
I have a function basically OIDC security service which calls an API for fetching user details. I need this function at different places. I want to reuse this function and do some processing at 3 different places depending on conditions but since I cannot call subscribe on already subscribe function, Is there a way to achieve this without writing this piece of code again and again?
fetchUserDetails(){
// If it is null call oidc service
this.oidcSecurityService.getUserData().subscribe(
(userData: any) => {
if (userData) {
return userData
}
});
return null;
}
If I directly call the function and do some processing, the error I get is userData is null.
Upvotes: 1
Views: 378
Reputation: 96891
It largely depends on what you want to do but you can use share()
(or maybe shareReplay()
) before subscribing:
fetchUserDetails() {
// If it is null call oidc service
const obs$ = this.oidcSecurityService.getUserData().share();
obs$.subscribe(
(userData: any) => {
if (userData) {
return userData
}
});
return obs$;
}
Upvotes: 1