[英]Why do Angular guards behave differently when using @select from @angular/redux-store
canLoad
和canActivate
@select
從@ angular-redux / store獲得了相同的可觀察@select
問題 :為什么canActivate
可以與@select
返回的可觀察值canActivate
工作,而canLoad
中斷了所有路由? 兩名警衛有什么區別?
相關角度問題: https : //github.com/angular/angular/issues/18991
認證衛士
@Injectable()
export class AuthGuard implements CanLoad, CanActivate {
@select() readonly authenticated$: Observable<boolean>; // @angular-redux/store
canLoad(): Observable<boolean> | boolean {
// return true; // works
return this.authenticated$; // ERROR: all routing stops from and to the current page
}
canActivate(): Observable<boolean> | boolean {
// return true; // works
return this.authenticated$; // works
}
}
應用程序路由模塊
const routes: Routes = [
{
path: '',
component: SomeAComponent,
pathMatch: 'full'
},
{
path: 'someb',
component: SomeBComponent,
canActivate: [
AuthGuard
],
},
{
path: 'lazy',
loadChildren: './lazy/lazy.module#LazyModule',
canLoad: [
AuthGuard
]
},
{
path: '**',
redirectTo: '/'
}
];
我遇到了同樣的問題,因此要解決此問題並讓它同時在CanLoad和CanActivate中工作,您應該添加運算符take(1)
@Injectable()
export class AuthGuard implements CanLoad, CanActivate {
@select() readonly authenticated$: Observable<boolean>; // @angular-redux/store
canLoad(): Observable<boolean> | boolean {
// return true; // works
return this.authenticated$.pipe(take(1));
}
canActivate(): Observable<boolean> | boolean {
// return true; // works
return this.authenticated$;
}
}
我遇到了同樣的問題,但我確實認為這是一個有角度的錯誤。 我最終只是重寫了我的后衛,以存儲通過訂閱Observable填充的局部變量。 我在這里使用ngrx / store。
@Injectable()
export class MustBeAuthenticatedGuard implements CanActivate, CanLoad {
constructor(private store: Store<fromAuth.State>) {
store.select(fromAuth.authenticated)
.subscribe((authenticated) => {
this.authenticated = authenticated;
});
}
private authenticated: boolean
canLoad(): boolean {
return this.isAuthenticated();
}
canActivate(): boolean {
return this.isAuthenticated();
}
private isAuthenticated() {
if (!this.authenticated) {
this.store.dispatch(new SignIn());
}
return this.authenticated;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.