gpt4 book ai didi

angular - 使用 props 在 createSelector ngrx 中过滤

转载 作者:行者123 更新时间:2023-12-04 04:24:22 25 4
gpt4 key购买 nike

我正在尝试创建一个简单的选择器以通过 visitor_id 获取存储中的所有消息然而,在 ngrx 中实现看起来如此简单的事情总是具有挑战性。

我正在使用 ngrx 实体,所以我已经有了 selectAll选择器准备好,所以我尝试执行以下操作:

export const selectMessagesState = createFeatureSelector<MessagesState>('messages');

export const selectAllMessages = createSelector(
selectMessagesState,
fromMessage.selectAll
);

export const selectMessageByVisitorId = createSelector(
select(selectAll),
(visitor_id) => map(val => val.filter(c => c.visitor_id == visitor_id))
);

并在组件中:

export class Message {
id: number;
message: string;
visitor_id: number;
is_from_visitor: boolean;
created_at: string;
}
public messages$ : Observable<Message[]>;

public showThread(visitor: Visitor){

this.messages$ = this.store.select(selectMessageByVisitorId({ visitor_id: visitor.id}));


但是我收到了 Property 'filter' does not exist on type 'unknown'selectMessageByVisitorId .我很确定我没有遵循正确的方法。我想要做的很简单,传递一个 visitor idselectMessageByVisitorId selectir,它返回特征存储中的消息列表,由 visitor_id 过滤.

更新 #1

根据@Nikhil 的建议,我将选择器更改为:

export const selectMessageByVisitorId = ({visitor_id}) => createSelector(
select(selectAll),
messages => messages.filter(val => val.visitor_id == visitor_id)
);

但是我收到了 Property 'filter' does not exist on type 'Observable<Message[]> , 事件虽然我进口了 import { filter} from 'rxjs/operators'; (我使用 ngrx 8.0)。

所以我想尝试:

export const selectMessageByVisitorId = ({visitor_id}) => createSelector(
select(selectAll),
messages => messages.pipe(
map(val => val.filter(c => c.visitor_id == visitor_id) )
)
);

但现在我得到 Type 'Observable<Observable<Message[]>>' is not assignable to type 'Observable<Message[]>'.在组件文件中 this.messages$ = this.store.select(selectMessageByVisitorId({ visitor_id: visitor.id}));

最佳答案

map()这里不需要,只需使用 filter() .

方法一:

export const selectMessageByVisitorId = ({visitor_id}) => createSelector(   
pipe(
select(selectAll),
filter(val => val.visitor_id == visitor_id)
)
);

方法二:
export const selectAllMessages =  createSelector(
selectMessagesState,
fromMessage.selectAll
);

export const selectMessageByVisitorId = ({visitor_id}) => createSelector(
selectAllMessages,
messages => messages.filter(val => val.visitor_id == visitor_id)
);

然后订阅消息。
this.messages$ = this.store.select(
selectMessageByVisitorId({visitor_id: visitor.id})
);

this.messages$.subscribe((messages) => {
// Handle response.
console.log(messages);
});

关于angular - 使用 props 在 createSelector ngrx 中过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58148915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com