Angular、NgRx 如何在 ngOnInit 中使用 RxJS 运算符

标签 angular rxjs ngrx ngrx-store

我有一个小问题需要理解 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/

相关文章:

Angular2 模板 - 使用变量不在此

javascript - Observables 的 Angular HttpClient 默认错误函数

javascript - NGRX:创建多个 reducer react 的 "global"操作的正确方法?

javascript - 是否可以在现有服务器上使用服务器端渲染?

angular - 在 Angular 4 中实现包装器组件的正确方法?

angular - 如何取消订阅 ngrx/store?

angular - NGRX - 使用哈希而不是数组作为状态

angular - 每次初始化组件时从 Behavior Subject 接收多个数据实例

javascript - 如何从无限的 RxJs 流中获取不是初始值的单个最新值?

angular - Ngrx Store 在浏览器刷新后重置。如何让应用保持状态?