如何将过滤器与 switchMap 一起使用?

Kev*_*one 3 rxjs typescript angular

我有一个可观察的对象,它应该监视具有类型的每条聊天消息'private'

所以我想做的是使用filter()rxjs 中的函数来观察每个具有类型的聊天消息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')
      )
    );
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:Type 'string' is not assignable to type 'boolean'

我如何使用filter()该类型获取所有 ChatMessage 'private'

Har*_*maz 5

filterRxJS v6+ 的(我假设你使用 v6+)是一个可管道操作符。所以你需要像这样使用它:

this.chatMessageService.getAllByChatRoomUid$(chatRoom.uid).pipe(
   filter(cr => cr.type === 'private')
);
Run Code Online (Sandbox Code Playgroud)

进一步阅读: https: //www.learnrxjs.io/operators/filtering/filter.html


更新:

由于响应是一个数组,因此您需要使用Array.filter. 你可以像下面这样做:

this.chatMessageService.getAllByChatRoomUid$(chatRoom.uid).pipe(
   map(crArr => crArr.filter(cr => cr.type === 'private'))
);
Run Code Online (Sandbox Code Playgroud)