我正在尝试从 Angular Guard 中的 ngrx 存储中选择两个字段,如下所示:
@Injectable()
export class RoleGuard implements CanActivate {
constructor(
public router: ActivatedRouteSnapshot,
private store: Store<AppState> ) {}
canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
const expectedRole = route.data.Role;
return combineLatest(
this.store.pipe(select(isLoggedIn)),
this.store.pipe(select(currentUser)),
).pipe(
tap( ([loggedIn, user]) =>
{
if ( loggedIn && !(user.role.find(expectedRole) >= 0) ) {
this.router.navigateByUrl('/error/403')
};
}
)
);
}
}
但是,我得到 Type 'boolean | [any, any]' 不可分配给类型 'boolean'
,这是有道理的,因为 combineLatest 返回数组中的结果。但我似乎找不到比 combineLatest 更优雅的方法,而不是嵌套两个 select observable,我在这里有什么选择?
最佳答案
canActivate
方法应该返回一个包含在 Observable
中的 boolean
。根据您的代码,它返回包装在从 combineLatest
方法返回的 Observable
中的值,该方法是一个数组。您可以使用 map
运算符返回 true
或 false
,如下所示:
@Injectable()
export class RoleGuard implements CanActivate {
constructor(
public router: ActivatedRouteSnapshot,
private store: Store<AppState> ) {}
canActivate(route: ActivatedRouteSnapshot): Observable<boolean> {
const expectedRole = route.data.Role;
return combineLatest(
this.store.pipe(select(isLoggedIn)),
this.store.pipe(select(currentUser)),
).pipe(
map( ([loggedIn, user]) =>
{
if ( loggedIn && !(user.role.find(expectedRole) >= 0) ) {
this.router.navigateByUrl('/error/403')
//I am assuming that you want to fail the guard and want your application to route to 403 page, so let’s return false
return false;
};
//I am assuming that you want to pass the guard of above if condition fails, so return true; bottom line is to return true/false as per your logic.
return true;
}
)
);
}
}
希望对您有所帮助。
关于javascript - 链二选择 rxjs store in Angular Guard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57446818/