我有一个小问题需要理解 RxJS 运算符与 NgRx 的结合。下面我有一个带有 NgRx 存储的简单组件 - 那里有所有必要的数据并且选择器工作正常:
export class TestComponent implements OnInit {
selector1$: Observable<any>;
selector2$: Observable<any>;
constructor(private store$: Store<StoreModel>) {
}
ngOnInit() {
selector1$ = this.store$.pipe(select(selectValue1));
selector2$ = this.store$.pipe(select(selectValue1));
}
}
但是 - 我想使用 RxJS 运算符 - 例如使用 withLatestFrom
并调用 2 个选择器 - 我应该从哪里开始 .pipe
?
我。
ngOnInit() {
pipe(
withLatestFrom(
this.store$.pipe(select(selectValue1));
this.store$.pipe(select(selectValue2));
),
map(([respValue1, respValue2]) => {}
}
二.或者通过 this.store$
:
this.store$.pipe(
withLatestFrom(
this.store$.pipe(select(selectValue1));
this.store$.pipe(select(selectValue2));
),
map(([respValue1, respValue2]) => {}
}
三.或像 I./II。但使用箭头?
this.store$.pipe(combineLatest(
this.store$.pipe(select(selectValue1)),
this.store$.pipe(select(selectValue2)),
(respValue1, respValue2) => {
return `${respValue1} + ${respValue2}`})).subscribe(console.log);
所有解决方案均无效。我应该为调用 RxJS 运算符创建新的可观察值吗?或者这种情况的最佳解决方案是什么。
提前谢谢您。
最佳答案
withLatestFrom()
不是“Observable 创建方法”,因此您可能需要使用 combineLatest()
(另外,withLatestFrom()
的工作方式与 combineLatest()
不同)。
combineLatest([
this.store$.pipe(select(selectValue1)),
this.store$.pipe(select(selectValue1)),
]).subscribe(([result1, result2]) => {
// do whatever you want here
})
关于Angular、NgRx 如何在 ngOnInit 中使用 RxJS 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60059459/