如何使 EPIC 完全动态

问题描述 投票:0回答:1

我使用 Angular 2 和 redux/store 以及 redux-observable 来形成史诗。我想要做的是一个通用的轮询器,所以我只需要编写一次轮询器。我有大约 25 个服务,我宁愿让操作传递什么类型的操作,以及它将执行的服务,然后使用重复的代码并编写大量的 case 或 if 语句:

我目前拥有的代码:

startPoller: Epic<Action<void>, Action<void>> = action$ =>
    action$.ofType(BankActions.DEPOSIT.POLL_DATA)
      .switchMap(action =>
        Observable.interval(1000)
          .takeUntil(action$.ofType(BankActions.DEPOSIT.STOP_POLLING))
          .mergeMap(count =>
            this.bankService.getDeposit.(action.payload)
              .map(payload => ({ type: BankActions.DEPOSIT.POLL_SUCCESS, payload }))
              .catch(error => Observable.of({
                type: BankActions.DEPOSIT.POLLING_FAILED,
                payload: error
              }))
        )
)

我想用伪代码做什么:

startPoller: Epic<Action<void>, Action<void>> = action$ =>
    action$.ofType(BankActions.DEPOSIT.POLL_DATA || BankActions.WITHDRAW.POLL_DATA || InvestActions.STOCK_PRICE.POLL_DATA )
      .switchMap(action =>
        Observable.interval(1000)
          .takeUntil(action$.ofType(action.STOP_POLLING))
          .mergeMap(count =>
            this.bankService.getDeposit(action.payload)
              .map(payload => ({ type: BankActions.DEPOSIT.POLL_SUCCESS, payload }))
              .catch(error => Observable.of({
                type: BankActions.DEPOSIT.POLLING_FAILED,
                payload: error
              }))
        )
)

我猜要让它工作,我可能需要创建某种类型的基本类型,每个需要轮询的操作/服务都需要扩展,然后我可以检查 ifs 类型是“PollerService”还是类型“PollerEpic”并且那么我可以过滤它吗?

angular redux redux-observable
1个回答
1
投票

你问的问题有点不清楚,但我想我可以回答一些。

你的伪代码

ofType
:

action$.ofType(BankActions.DEPOSIT.POLL_DATA || BankActions.WITHDRAW.POLL_DATA || InvestActions.STOCK_PRICE.POLL_DATA )

可以通过将它们作为参数传递来完成;

ofType
将检查给定的操作是否属于这些类型中的任何一种。

action$.ofType(BankActions.DEPOSIT.POLL_DATA, BankActions.WITHDRAW.POLL_DATA, InvestActions.STOCK_PRICE.POLL_DATA )

我在伪代码中看到的下一件事是您希望匹配的操作提供

STOP_POLLING
类型。

.takeUntil(action$.ofType(action.STOP_POLLING))

尚不清楚

STOP_POLLING
的哪些值是可接受的,通常 redux 类型变量应命名为与字符串相同的名称,例如
STOP_POLLING = 'STOP_POLLING'
在这种情况下,这并不重要,因为它们都是相同的
'STOP_POLLING'
值。

如果您希望它们有所不同,我不会使用 UPPER_CASE 约定,因为这可能会使维护变得混乱:

// what an action _might_ look like
{
  type: BankActions.DEPOSIT.POLL_DATA,
  meta: {
    stopType: 'DEPOSIT_STOP_POLLING'
  }
}

// then used something like this:
.takeUntil(action$.ofType(action.meta.stopType))
© www.soinside.com 2019 - 2024. All rights reserved.