我已经创建了一个认证后卫我angular2 RC5的应用程序。
我也用终极版商店。 在那家店我保持用户的认证状态。
我读的保护可以返回一个可观察或承诺( 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);
});
}
}