I am currently working on creating a unique in-memory singleton that stores the vendor being viewed by a user.
A guard is implemented on all specific routes to capture 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 utilized to fetch the vendor by name. If it's present in memory, it's directly returned. Otherwise, it's fetched 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 issue lies in the fact that I need to verify vendor$
for its value returning an Obervable<IUser>
, but the switchMap also provides an Obervable<IUser>
, resulting in
Observable<Observable<IUser>>
. How can I ensure that the result
only returns a single User Observable?