【发布时间】:2016-09-02 10:30:42
【问题描述】:
我为我的 angular2 rc5 应用程序创建了一个身份验证保护。
我也在使用 redux 商店。在该商店中,我保留了用户的身份验证状态。
我读到守卫可以返回一个可观察或承诺 (https://angular.io/docs/ts/latest/guide/router.html#!#guards)
我似乎无法找到一种方法让守卫等到商店/可观察对象更新,并且只有 在 更新后才返回守卫,因为默认值商店的永远是假的。
第一次尝试:
@Injectable()
export class AuthGuard implements CanActivate {
@select(['user', 'authenticated']) authenticated$: Observable<boolean>;
constructor() {}
canActivate(): Promise<boolean> {
return new Promise((resolve, reject) => {
// updated after a while ->
this.authenticated$.subscribe((auth) => {
// will only reach here after the first update of the store
if (auth) { resolve(true); }
// it will always reject because the default value
// is always false and it takes time to update the store
reject(false);
});
});
}
}
第二次尝试:
@Injectable()
export class AuthGuard implements CanActivate {
@select(['user', 'authenticated']) authenticated$: Observable<boolean>;
constructor() {}
canActivate(): Promise<boolean> {
return new Promise((resolve, reject) => {
// tried to convert it for single read since canActivate is called every time. So I actually don't want to subscribe here.
let auth = this.authenticated$.toPromise();
auth.then((authenticated) => {
if (authenticated) { resolve(true); }
reject(false);
});
auth.catch((err) => {
console.log(err);
});
}
}
【问题讨论】:
-
以下任何答案都可以解决您的问题?
标签: javascript angular angular2-routing