如何使用当前状态值分派动作? [英] How to dispatch an action with current value of state?

查看:68
本文介绍了如何使用当前状态值分派动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个角度组件显示列表中的项目.可以选择每个 itemn,所选项目的 id 将存储在 state 中.所以我的状态对象看起来像这样:

I have an angular component showing items in a list. Each itemn can be selected and the ids of the selected items will be stored in the state. So my state object looks like this f.e.:

{ items: Item[]; selected: string[] }

现在我得到了一个名为 DeleteSelectedAction 的操作,它将 selected 作为有效负载.此操作将使用效果等调用某些 WebAPI.

Now I got an action called DeleteSelectedAction that gets selected as payload. This action will call some WebAPI using an effect and so on.

现在我找到了两种方法来做到这一点.

Now I found two ways how I could do this.

第一:从商店中选择selected并订阅它并通过操作传递值

First: Select selected from store and subscribe to it and pass the value with the action

store.select(fromItems.getSelected).subscribe(ids => {
    this.selected = ids; 
});
...
store.dispatch(new itemActions.DeleteSelectedAction(this.selected);

第二:不传递任何值到操作,但获取有效的selected

Second: Pass no value to action but fetch the selected in effect

store.dispatch(new itemActions.DeleteSelectedAction());

// in effect
@Effect()
delete$: Observable<Action> = this.actions$
  .ofType(fromItems.DELETE)
  .withLatestFrom(this.store.select(fromItems.getSelected)
  .switchMap([action, selected] => {
    return this.service.delete(selected)
      .map(new itemActions.DeleteSuccessAction())
      .catch(err => Observable.of(new itemActions.DeleteFailAction(err));
  });

我不喜欢第一种方式,因为我需要使用订阅并且需要正确取消订阅.第二种方法是可以的,但只有当动作有副作用时.所以现在我正在寻找第三种方式.在我的脑海中,这种方式如下所示:

I don't like the first way because I need to use a subscription and need to unsubscribe properly. The second way is ok but only when the action has side effects. So now I'm looking for a third way. In my head this way looks like the following:

store.dispatchWithLatestFrom(
  fromItems.getSelected,
  (selected) => new itemActions.DeleteSelectedAction(selected));

我怎么能用 rxjs 操作符得到类似的东西?

How could I get something like that with rxjs operators?

推荐答案

即使操作没有副作用,您的第二种方法也应该可以正常工作.使用 @Effect 在不执行副作用的情况下转换动作是对库的完全合法使用.在此处查看内容丰富部分.在这种情况下,我肯定会调用类似 DELETE_SELECTED 而不仅仅是 DELETE 之类的操作.

Your second approach should work just fine even if the action has no side effects. using an @Effect to transform an action without performing a side effect is a perfectly legitimate use of the library. See the section on Content Enrichers here. In that case, I'd definitely call the action something like DELETE_SELECTED rather than just DELETE.

这篇关于如何使用当前状态值分派动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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