I created an authentication protector for my angular2 rc5 application.
I also use redux store. In this store, I save user authentication status.
I read that a guard can return what is observed or promised ( https://angular.io/docs/ts/latest/guide/router.html#!#guards )
I can’t find a way for the guard to wait until the store / monitored is updated , and only after which it updates will return the guard, since the store’s default value will always be false.
First try:
@Injectable()
export class AuthGuard implements CanActivate {
@select(['user', 'authenticated']) authenticated$: Observable<boolean>;
constructor() {}
canActivate(): Promise<boolean> {
return new Promise((resolve, reject) => {
this.authenticated$.subscribe((auth) => {
if (auth) { resolve(true); }
reject(false);
});
});
}
}
Second attempt:
@Injectable()
export class AuthGuard implements CanActivate {
@select(['user', 'authenticated']) authenticated$: Observable<boolean>;
constructor() {}
canActivate(): Promise<boolean> {
return new Promise((resolve, reject) => {
let auth = this.authenticated$.toPromise();
auth.then((authenticated) => {
if (authenticated) { resolve(true); }
reject(false);
});
auth.catch((err) => {
console.log(err);
});
}
}
source
share