在ngrx/effects(redux-observable)中分派多个动作可以通过多种方式实现。以下是一些常见的方法:
mergeMap
操作符mergeMap
操作符允许你在Observable完成时执行多个动作。你可以使用它来分发多个动作。
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { mergeMap, map } from 'rxjs/operators';
import { Store } from '@ngrx/store';
import { someAction, anotherAction } from './actions';
@Injectable()
export class MyEffects {
constructor(
private actions$: Actions,
private store: Store
) {}
myEffect$ = createEffect(() =>
this.actions$.pipe(
ofType('[My Component] Do Something'),
mergeMap(() => [
store.dispatch(someAction()),
store.dispatch(anotherAction())
])
)
);
}
switchMap
操作符switchMap
操作符类似于mergeMap
,但它会在新的Observable到来时取消之前的Observable。这在处理异步操作时非常有用。
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { switchMap, map } from 'rxjs/operators';
import { Store } from '@ngrx/store';
import { someAction, anotherAction } from './actions';
@Injectable()
export class MyEffects {
constructor(
private actions$: Actions,
private store: Store
) {}
myEffect$ = createEffect(() =>
this.actions$.pipe(
ofType('[My Component] Do Something'),
switchMap(() => [
store.dispatch(someAction()),
store.dispatch(anotherAction())
])
)
);
}
exhaustMap
操作符exhaustMap
操作符会在当前Observable完成之前忽略新的Observable。这在处理需要顺序执行的动作时非常有用。
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { exhaustMap, map } from 'rxjs/operators';
import { Store } from '@ngrx/store';
import { someAction, anotherAction } from './actions';
@Injectable()
export class MyEffects {
constructor(
private actions$: Actions,
private store: Store
) {}
myEffect$ = createEffect(() =>
this.actions$.pipe(
ofType('[My Component] Do Something'),
exhaustMap(() => [
store.dispatch(someAction()),
store.dispatch(anotherAction())
])
)
);
}
这些方法在以下场景中非常有用:
通过这些方法,你可以在ngrx/effects中灵活地分派多个动作,以满足不同的业务需求。
领取专属 10元无门槛券
手把手带您无忧上云