LoginSignup
4
2

More than 5 years have passed since last update.

NGRXの一度のEffect内で複数回Actionを発生させたい

Last updated at Posted at 2019-01-22

例題

AActionを拾うAEffect内で

  • BAction
  • ServicecFuncを呼び出し及びその結果=CAction+エラーハンドラErrorAction
  • DAction

を順番に呼び出したい。

// import等は省略
// ActionTypes等は別途定義済とする

@Injectable()
export class MyEffect {
  constructor(
    private readonly actions$: Actions,
    private readonly service: Service,
  ) {}

  @Effect()
  aEffect$: Observable<Action> = this.actions$.pipe(
    ofType<AAction>(ActionTypes.AAction),
    switchMap(() =>
      concat(
        of(new BAction({})),
        this.service.cFunc().pipe(
          map(({ result }) => new CAction({ result })),
          catchError(error => of(new ErrorAction({ error }))),
        ),
        of(new DAction({})),
      ),
    ),
  );
}

switchMapからのconcatで順番保証しつつ、ofやらpipeからのmapおよびcatchErrorで複数回Actionを呼び出しています。

スマートではないけど、動いていてはいる。

順番にこだわらない場合はmergeでもいけると思う。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2