创建带有动态参数的重选选择器的问题

时间:2017-04-18 14:23:34

标签: reselect

我正在尝试将动态参数传递给重选器。原因是这个参数实际上是一个事先不知道的角度路径参数。它也不能成为国家的一部分。

以下是订阅组件中传递路由参数的相关代码:

this.store.select(fromRoot.getMessagesWithOtherUserAccount(this.route.params['otherId']))
      .subscribe(messages => this.messagesWithOtherUserAccount = messages);

以下是选择器的代码:

const getMessagesState = (state: State) => state.message.messages;

//See error below... How can I pass my otherId argument here??
const messagesWithOtherUserAccount = createSelector(getMessagesState, messagesWithCounterParty);

export const getMessagesWithOtherUserAccount = (otherId: number) => messagesWithOtherUserAccount(otherId);

....
export const messagesWithCounterParty = (messages: Message[]) => (otherId: number) => withOtherUserAccount(otherId, messages);

这是我得到的错误:

  

类型'number'的参数不能分配给类型的参数   '状态'。

我想将otherId参数传递给messagesWithOtherUserAccount createSelector,但我不确定如何......

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

我能够提出以下解决方案:

this.store.select(fromRoot.getMessagesWithCounterParty(this.route.snapshot.params['otherId']))
  .subscribe(messages => this.messagesWithOtherUserAccount = messages);

export const getMessagesWithCounterParty = (otherId: number) => createSelector(getMessagesState, (messages: Message[]) => withOtherUserAccount(otherId, messages));

答案 1 :(得分:0)

createSelector可以创建能够接受任意数量的自定义/动态参数的选择器!请参阅createSelector API

在您的情况下,获得结果的伪代码可能是:

// ...

export const getMessagesWithCounterParty = createSelector(
    getMessagesState,               // Accepts the state as 1st argument
    (otherId: number) => otherId,   // Accepts an Id as 2nd argument

    // Result function
    (messages: Message[], otherId: number) => withOtherUserAccount(messages, otherId),
);

// Later in your application:
getMessagesWithCounterParty(yourState, 42);

PS。您得到的错误不是来自您的应用程序,而是来自您的类型检查程序(可能是Typescript)。