angular - 如何在 Angular Guard 中使用 CombineLatest 和 Ngrx
问题描述
我正试图等待几个状态true
在我的保护之下。
我试过这样:
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
return combineLatest([
this.store.select(
fromStore.selectProductsLoaded
),
this.store.select(fromStore.selectArticlesLoaded),
]).pipe(
map(([a, b]) => ({ a, b })),
filter(({ a, b}) => a && b),
first()
);
}
我需要这两个数据,true
所以我想使用combineLatest
但遇到了这个错误:
Type 'Observable<{ a: boolean; b: boolean; }>' is not assignable to type 'Observable<boolean>'
相比之下,这有效:
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
return this.store
.select(fromStore.selectProductsLoaded)
.pipe(
filter((loaded) => loaded),
take(1)
);
}
解决方案
你得到这个错误的原因是因为使用 combineLatest 你传递了一个 observables 数组,然后将它映射到结构 {a: boolean, b: boolean} 的对象。
我猜你想根据这两个输入返回一个布尔值。
所以一个可能的解决方案可能是
.pipe(
map(([a, b]) => ({ a, b })),
filter(({ a, b}) => a && b),
map(values => {
// both a and b are true
if(values.a && values.b){
return true;
} else {
return false;
}
}),
first()
);
推荐阅读
- r - 如何将 .txt 冒号分隔的键值对列表转换为以段落分隔的大小写(Rstudio)
- c# - 如何使用 c# 更新 cosmos db 文档
- lua - 给定 lua 脚本中 for 循环语法的解释
- r - 使用 R 动画包含条形图和折线图
- lua - 如何修复 Roblox 无限收益错误?
- python - Django ElasticSearch 仅返回 10 个行集
- javascript - 我想通过循环或其他方式随机更改 Google Marker 位置
- c# - Asp.Net 使用引导模式弹出窗口插入
- deep-learning - Pytorch 中自定义 LSTM 模型的输出维度
- java - @RepositoryRestResource 不起作用 Spring boot 2.2.1.RELEASE。运行时发生错误 RegionRepository 必须只包含单个路径段