I'm trying to create an in-memory singleton that holds the current vendor a person is browsing on.
A guard is used on all specific routes to catch the parameter:
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> {
let currentUrl = this._router.url;
const param = route.params['vendname'];
return this._vendorService.getByName(param).pipe(map(a => {
if (a == null) {
this._snackBarService.open('Vendor not found', 'x', { duration: 5000 });
return this._router.parseUrl(currentUrl);
}
return true;
}));
}
A service is used to get the vendor by name. If it exists in-memory return it. If it doesn't, get it from the server first.
set vendor(value: IUser) {
this._vendor.next(value);
}
get vendor$(): Observable<IUser> {
return this._vendor.asObservable();
}
getByName(name: string): Observable<IUser> {
const result = this.vendor$.pipe(map(v => {
if (v != null && v.displayName == name) {
return v;
}
else {
return this.Get<IUser>(`api/vendor/${name}`).pipe(switchMap(v => {
this.vendor = v;
return of(v)
// ...
}));
}
}))
return result;
}
The problem is I need to check vendor$
for its value which returns an Obervable<IUser>
but the switchMap also returns an Obervable<IUser>
, causing the result to be Observable<Observable<IUser>>
. How can I make the result
return a single User Observable?