首页 > 解决方案 > Angular,NgRx 如何在 ngOnInit 中使用 RxJS 运算符

问题描述

我有一个小问题要理解将 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 运算符创建新的可观察值吗?或者这种情况的最佳解决方案是什么。

先感谢您。

标签: angularrxjsngrxngrx-store

解决方案


withLatestFrom()不是“可观察的创建方法”,因此您可能希望combineLatest()改用(另外,withLatestFrom()工作方式与 不同combineLatest())。

combineLatest([
  this.store$.pipe(select(selectValue1)),
  this.store$.pipe(select(selectValue1)),
]).subscribe(([result1, result2]) => {
  // do whatever you want here
})

推荐阅读