如何链接rxjs可观察对象以获取内部可观察对象的值并在Angular中与父对象一起返回

时间:2020-09-06 22:57:58

标签: angular firebase google-cloud-firestore rxjs observable

我向firestore发送请求以获取用户的聊天记录,并返回具有这种形状的可观察对象数组

[...,
  {
     key: '83hed87djhe09',
     participants: ['owner_43', 'visitor_69']
  },
...]

这将在UI中显示所有用户聊天的列表,但是我想按用户名搜索聊天。为此,我必须向后端服务器发出一个http请求,以获取每个参与者的用户名,然后将其替换为参与者线程中的名称,以使其在类型上可搜索。

例如,“ owner_43”将变成“ John Doe”。

我遇到的问题是我得到了参与者姓名的可观察值数组,而不是字符串数组。

enter image description here

这是我的代码

this.chat$ = this.chatSvc.getUserChats(this.userUID).pipe(
  map((chats: any) => {
    return chats.map((chat: any) => {
      return {
        key: chat.key,
        participants: chat.participants.map((participant: any) => {
          return this.userSvc.getUserFromString(participant);
        })
      }
    })
  })
);

这是getUserFromString函数:

getUserFromString(stringId){

  let splitValue = stringId.split("_");
  let accountType = splitValue[0];
  let id = splitValue[1];

  if (accountType === 'owner') {
    return this.ownerSvc.getOwner(id);
  }
  else if (accountType === 'visitor') {
    return this.visitorSvc.getVisitor(id);
  }
}

获取所有者函数仅返回:

return this.http.get(owner_url + id);

最后,使用角度异步管道将结果在视图中展开

<ul><li *ngFor="let msg of chat$|async">{{msg.key}}</li></ul>

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

假设您的Chat如下所示:

/**
 * Type parameter is being used
 * due to participants initially being of type string[]
 * and ultimately of type User[]
 */
class Chat<T> {
  key: string;
  participants: T[]
}

考虑以下实现:

this.chat$: Observable<Chat<User>[]> = this.chatSvc.getUserChats(this.userUID).pipe(
  mergeAll(),
  mergeMap(({ key, participants }: Chat<string>) => {
    return forkJoin(participants.map(this.userSvc.getUserFromString)).pipe(
      map(participants => ({ key, participants }))
    )
  }),
  toArray()
)

说明(简体):

this.chat$ = this.chatSvc.getUserChats(this.userUID).pipe(

/**
 * flattens Observable<Chat[]> into a stream
 * of Observable<Chat> so we can handle single Chat at a time
 */
  mergeAll(), 

 /**
  *  transform each Chat into an 
  *  Observable containing a new value
  */
  mergeMap(({ key, participants }: Chat) => {

   /**
    * transform participants (String[]) into an array of Observables 
    * (Observable<User>[])
    */
    const participants$ = participants.map(this.userSvc.getUserFromString)
    
   /**
    *  wait for all Observables to complete using forkJoin
    *  then return new Chat using map
    */
    return forkJoin(participants).pipe(
      map(participants => ({ key: key, participants: participants  }))
    )
  }),
  toArray() // <= transform stream back into array (Observable<Chat[]>)
)