我有一个 observable,它应该监视每个类型为 'private'
所以我想做的是使用 rxjs 中的函数 filter()
来观察每个类型为 private
的聊天消息,这样我就可以使用它在我的变量 chatMessagePrivate$
这是我尝试过的:
export type ChatType = 'private' | 'standard';
export class ChatMessage {
uid?: string;
chatRoomUid: string;
type: ChatType;
}
chatMessagePrivate$: Observable<ChatMessage[]>;
ngOnInit() {
this.chatMessagePrivate$ = this.chatRoom$.pipe(
switchMap((chatRoom: ChatRoom) => this.chatMessageService.getAllByChatRoomUid$(chatRoom.uid) // this function returns every message from the uid of the chatroom
.filter(chatRoom => 'private')
)
);
}
我收到以下错误:Type 'string' is not assignable to type 'boolean'
如何使用 filter()
获取类型为 'private'
的所有 ChatMessage?
最佳答案
filter
的 RxJS v6+(我假设你使用的是 v6+)是一个管道运算符。所以你需要像这样使用它:
this.chatMessageService.getAllByChatRoomUid$(chatRoom.uid).pipe(
filter(cr => cr.type === 'private')
);
进一步阅读:https://www.learnrxjs.io/operators/filtering/filter.html
更新:
由于响应是一个数组,你需要使用Array.filter
。你可以像下面那样做:
this.chatMessageService.getAllByChatRoomUid$(chatRoom.uid).pipe(
map(crArr => crArr.filter(cr => cr.type === 'private'))
);
关于angular - 如何在 switchMap 中使用过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57770645/