Angular 中的 ngRx 库提供了一种处理应用程序状态的强大机制。当我们需要在第一个 Action 执行完毕后,将其产生的数据传递给第二个 Action 时,可以通过使用 RxJS 操作符来实现。下面是一个示例代码,展示了如何使用 combineLatest 操作符来完成这个任务:
import { Actions, ofType } from '@ngrx/effects';
import { Injectable } from '@angular/core';
import { Action } from '@ngrx/store';
import { Observable, combineLatest } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
@Injectable()
export class MyEffects {
constructor(private actions$: Actions) {}
// 第一个 Action
firstAction$: Observable = this.actions$.pipe(
ofType('FIRST_ACTION_TYPE'),
map((action: any) => action.payload)
);
// 第二个 Action
secondAction$: Observable = combineLatest(
this.actions$.pipe(ofType('FIRST_ACTION_TYPE')),
this.someOtherService.getData() // 获取第一步数据,并传递给第二个Action
).pipe(
switchMap(([action, data]) => {
// 在这里操作第二个 Action
})
);
}
在上面的代码中,通过使用 combineLatest 操作符,我们在第一个 Action 完成后,调用了第二个 Action,并将第一个 Action 产生的数据传递给后者。由于 combineLatest 操作符会将所有流中最后发出的值作为参数传递给其回调函数,因此我们可以在它的回调函数中访问这个数据,并在其中操作第二个 Action。