等待组件 ngrx store 中的两个动作

Wait for two actions inside component ngrx store

我有 2 个名为 METADATA_SUCCESS_ACTION_1 和 SUCCESS_ACTION_2 的操作。 我如何才能等待这 2 个操作完成,然后订阅合并数据。

this.actions
  .pipe(
    ofType(METADATA_SUCCESS_ACTION_1),
    take(1)
  )
  .subscribe((data1: any) => {
    console.log(data1)
  });

this.actions
  .pipe(
    ofType(SUCCESS_ACTION_2),
    take(1)
  )
  .subscribe((data2: any) => {
    console.log(data2)
  });

我想等待这两个成功发生,然后处理作为元数据的数据和成功数据

听起来你可以在这里使用 forkJoin 运算符(当所有 observables 完成时,发出每个 observables 的最后一个发射值。)。来自文档:

Why use forkJoin?

This operator is best used when you have a group of observables and only care about the final emitted value of each. One common use case for this is if you wish to issue multiple requests on page load (or some other event) and only want to take action when a response has been receieved for all. In this way it is similar to how you might use Promise.all.

Be aware that if any of the inner observables supplied to forkJoin error you will lose the value of any other observables that would or have already completed if you do not catch the error correctly on the inner observable. If you are only concerned with all inner observables completing successfully you can catch the error on the outside.

It's also worth noting that if you have an observable that emits more than one item, and you are concerned with the previous emissions forkJoin is not the correct choice. In these cases you may better off with an operator like combineLatest or zip.

要使用它,您可以在上面的示例中使用以下代码。

forkJoin(
  this.actions.pipe(ofType(METADATA_SUCCESS_ACTION_1), take(1)),
  this.actions.pipe(ofType(SUCCESS_ACTION_2), take(1))
).subscribe(([data1, data2]) => {
  console.log(data1);
  console.log(data2);
})