How can I toggle (start/ stop) an ngrx action?

心已入冬 提交于 2020-06-28 07:39:32

问题


Below is an action that dispatches a load action to the store. The corresponding effect will handle the request and sends back the response items.

But What I want is I want to toggle the below action with a button.

So if I press start it will start dispatching actions every 1 s and if I press pause, it will pause dispatching and again If I press start it will continue from where it left, and repeats so...

How can I toggle such an action?

    let date = 1587513626000; // date is required because the backend only sends data with a start and end date
    interval(1000).pipe(tap(_ => {
      this.store.dispatch(loadStoreItems({ limit: 10, start: date, end: date + 1000 }))
      date += 1000
    }))
      .subscribe()

I've tried a bunch of operators, some of them are partially working (like sometimes using takeWhile/ takeUntil I'm being able to pause) but not being able to restart.


回答1:


to have a toggle in an effect you need 2 actions (start and stop) and to use takeUntil.

//effects.ts

  loadCourierItems$ = createEffect(() =>
    this.actions$.pipe(
      ofType(actions.start),
      exhaustMap(action => interval(1000).pipe(
        // logic for every second activity.
        map(actions.everySecondAction()),
      )),
      takeUntil(this.actions$.pipe(ofType(actions.stop))),
      repeat(),
    )
  )
//app.component.ts

  constructor(private store: Store<CourierItemsState>) {
  }

  ngOnInit() {
    this.store.dispatch(startAction());
  }

  ngOnDestroy() {
    this.store.dispatch(stopAction());
  }


来源:https://stackoverflow.com/questions/61427341/how-can-i-toggle-start-stop-an-ngrx-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!