withLatestFrom() returns 整个状态

withLatestFrom() returns the whole state

我有以下代码:

@Select(CustomerState.customerProducts) customerProducts$: Observable<CustomerProduct[]>;

this.layouts$ = this.store.dispatch([
      new LoadCustomerProducts(),
    ]).pipe(
      withLatestFrom(this.customerProducts$),
      map(([customerProducts]) => {
        console.log('CP!!!', customerProducts);
        return this.loadLayouts(customerProducts);
      })
    );

问题是,当我记录 customerProducts 时,我期望它只会 return 客户产品数组,而不是 return 整个状态。为什么会这样?

谢谢!

withLatestFrom 将提供的 Observable 中的值推送到您使用 map 解构的数组中。如果 store.dispatch 在 ngxs returns 商店 Observable,你想要:

this.layouts$ = this.store.dispatch([
      new LoadCustomerProducts(),
    ]).pipe(
      withLatestFrom(this.customerProducts$),
      map(([store, customerProducts]) => {
        console.log('CP!!!', customerProducts);
        return this.loadLayouts(customerProducts);
      })
    );

参见:https://rxjs.dev/api/operators/withLatestFrom

值得注意的是withLatestFrom 不会等待customerProducts$发射。相反,当您订阅 layouts$ 时,您将立即获得当前状态,但由于 customerProducts$ 尚未发出,因此 layout$ 不会发出。

https://stackblitz.com/edit/rxjs-efmtxp