如何切换(开始/停止)一个ngrx操作? [英] How can I toggle (start/ stop) an ngrx action?

查看:68
本文介绍了如何切换(开始/停止)一个ngrx操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是将加载操作分派到商店的操作.相应的效果将处理请求并发回响应项.

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.

因此,如果我按开始,它将每1 s开始调度动作,如果我按一下暂停,它将暂停调度,然后再次按一次,如果我按开始,它将从它的左边继续,并重复如此...

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...

如何切换此类动作?

    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()

我尝试了很多操作符,其中一些操作符部分起作用(例如有时可以使用takeWhile/takeUntil,直到我能够暂停),但无法重新启动.

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.

推荐答案

要在效果中进行切换,您需要执行2个操作(开始和停止)并使用 takeUntil .

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());
  }

这篇关于如何切换(开始/停止)一个ngrx操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆