When I reload my page, it always goes to blank page instead of the same page. The reason behind this is canActivate method which is cheking for user's permission gets invoked as soon as user refreshes the page and it is not able to get user data immediately. User data comes after some seconds. Is there any way to make canActivate method wait till data comses? I have been going through RxJS's page but not understanding how to do it. Can someone suggest me any ideas?
constructor(private router: Router, private userDataService: UserDataService) {
userDataService.userData$.subscribe(
(data: User) => {
this.userData = userData --> comes after some seconds
}
);
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree
{
const result = this.getUserData(route);
if (!result) {
this.blankPage();
}
return result;
}
public getUserData(): Observable<boolean> {
if (this.userData) {
check for permissions...
return of(true);
}
return of(false);
}
userdata.service.ts:
userDataSubscription: Subscription;
userData: BehaviorSubject<User> = new BehaviorSubject<User>(null);
public userData$: Observable<User> = this.userData.asObservable();
private getUserData(): void {
const userData$ = new Observable(
subscriber => subscriber.next(new User())
).pipe(
delay(1000),
mergeMap((model: User) => this.getUserInfo(model)),
mergeMap((model: User) => this.getUserPermission(model)),
catchError((err, caught) => {
console.error('failed')
return caught;
})
);
this.userContextDataSubscription = userData$.subscribe(
(data: User) => {
this.userData,next(model);
},
() => console.error('failed')
);
}