I have the following code that is functional and works as intended.
canActivate(route: ActivatedRouteSnapshot): Observable<UrlTree | boolean> {
return new Observable<UrlTree | boolean>((observer) => {
this._authorizedStore
.select(selectProfile)
.pipe(take(1))
.subscribe((profile) => {
if (!profile) {
this._authorizedStore.dispatch(
AuthorizedActions.loadProfile({ userId: this._authenticationApi.getUser().id }),
);
}
this._authorizedStore
.select(selectAuthorizedState)
.pipe(first(state => !!state.profile))
.subscribe((state) => {
if (state.profile.profiles.length > 0) {
observer.next(true);
} else {
observer.next(this.router.createUrlTree(['./settings']));
}
observer.complete();
});
});
});
}
My goal is to find a more elegant and efficient way to achieve the same functionality. Essentially, I want to first check for the presence of a profile. If it doesn't exist, I need to trigger a request and then wait for its completion. It's worth mentioning that I'm using Ngrx, and if I don't use take(1) initially, it could lead to an infinite loop situation (no profile, make request, no profile, make request...).
Any suggestions on how to improve this process?