使用 props 在 createSelector ngrx 中过滤

filter in createSelector ngrx with props

我正在尝试创建一个简单的选择器来通过 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}));

但是我在 selectMessageByVisitorId 中得到了 Property 'filter' does not exist on type 'unknown'。我很确定我没有遵循正确的方法。我想做的很简单,将 visitor id 传递给 selectMessageByVisitorId 选择器,它 returns 特征存储中的消息列表,由 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);
});