如何在switchMap中使用过滤器?

时间:2019-09-03 11:20:51

标签: angular typescript rxjs

我有一个可观察对象,应该观看每条'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?

3 个答案:

答案 0 :(得分:4)

RxJS v6 +的

filter(我假设您使用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'))
);

答案 1 :(得分:2)

.filter()期望有boolean,因此请尝试以下操作:

.filter(chatRoom => chatRoom.type === 'private')

IF this.chatMessageService.getAllByChatRoomUid$(chatRoom.uid)返回一个Observable,那么您可能必须使用pipe

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 => chatRoom.type === 'private')
  )
);

答案 2 :(得分:1)

如果您应该使用redux操作,则可以使用RxJS中的特殊ofType过滤器来检索所有聊天类型等于“ private”的操作。

this.chatMessagePrivate$ = this.chatRoom$.pipe(
    ofType('private'),
    switchMap((chatRoom: ChatRoom) => this.chatMessageService.getAllByChatRoomUid$(chatRoom.uid) // this function returns every message from the uid of the chatroom
      )
    );

否则,如果没有redux,并且如果this.chatRoom$已经包含了聊天室是否私有的信息,建议您在实际服务方法调用之前附加filter

this.chatMessagePrivate$ = this.chatRoom$.pipe(
    filter(chatRoom:  => chatRoom.type === 'private'),  // in case the "type" property exists
    switchMap((chatRoom: ChatRoom) => this.chatMessageService.getAllByChatRoomUid$(chatRoom.uid)
    );