I have next method in my class which implements from CanActivate:
export class CanActivateLoginedInforamtion implements CanActivate {
constructor(private store: Store<AppState>) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>{
return timer(10000).pipe(
() => this.store.select(({ user: { loginState }}) => {
console.log(loginState);
return loginState === 'LOGINED'
})
);
}
}
But, my store.select returning instantly and not waiting ten seconds, why?
When used promise:
export class CanActivateLoginedInforamtion implements CanActivate {
constructor(private store: Store<AppState>) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Promise<boolean>{
return new Promise((resolve) => {
this.store.select(({ user: { loginState }}) => {
console.log(loginState); resolve(loginState === 'LOGINED');
})
})
}
}
This is the observable equivalent to your promise based example:
export class CanActivateLoginedInforamtion implements CanActivate {
constructor(private store: Store<AppState>) {}
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> {
return this.isLoggedIn();
}
private isLoggedIn(): Observable<boolean> {
return this.store.select(({ user: { loginState }}) => {
return loginState === 'LOGINED';
});
}
}
this.store.select()
is returning Observable<boolean>
, so you can simply return that from canActivate
. I have moved the store query to a new function to hopefully make it a little clearer.
If, for some reason, you want to wait 10 seconds before making the call, you can query your store after timer
has elapsed using switchMap
in the pipe. This is equivalent to chaining promises.
You will also need to use take(1)
to limit the number of timer events you want to receive.
export class CanActivateLoginedInforamtion implements CanActivate {
constructor(private store: Store<AppState>) {}
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> {
return timer(10000).pipe(
take(1),
switchMap(() => this.isLoggedIn())
);
}
private isLoggedIn(): Observable<boolean> {
return this.store.select(({ user: { loginState }}) => {
return loginState === 'LOGINED';
});
}
}