【问题标题】:How to modify inner element of each Object emitted by observable before returning the outer observable如何在返回外部可观察对象之前修改可观察对象发出的每个对象的内部元素
【发布时间】:2020-11-05 06:49:38
【问题描述】:

我对 Observables 和 rxjs 的整个概念很陌生,所以这可能非常明显。但是请帮忙,因为我很想学习

当用户在博客文章下点击显示 cmets 时,我有一个功能

 showComments(){
    
    this.firestoreservice.getComments(this.job.id).subscribe( data =>{
      this.comments = data //type [] of comment objects with (message,posterID,timeposted...)
    })

    this._showcomments = true;

  }

此函数调用一个服务函数,该函数将一个可观察对象返回到该作业的我的 cmets 列表中。 在订阅那个 observable 时初始化一个变量来保存我所有的 cmets。 但是,在我这样做之前,有没有办法用匹配的用户名替换每个评论的 posterID 属性?请参阅下面的预期结果:

showComments(){
   
   this.firestoreservice.getComments(this.job.id).subscribe( data =>{

     //for each comment held in data, replace comment.posterID with getUserName(posterID)
     //getUserName(posterID) will also return an observable which emmits one string
     //then append comment to comments list (or add back in to data then destructively assign 
     //comments=data )
     
     this.comments = data //type [] of comment objects with (message,posterID,timeposted...)
   })

   this._showcomments = true;

 }

【问题讨论】:

    标签: angularjs rxjs observable angularfire rxjs-observables


    【解决方案1】:

    它看起来有点像这样......

    this.firestoreservice.getComments(this.job.id).pipe(
      switchMap(comments => { // switchMap to subscribe to inner
        const getUsers$ = comments.map(comment => // array map comments into userName fetch
          this.firestoreservice.getUserName(comment.posterID).pipe(
            // once you have the username, rx map back into the comment with the username assigned
            map(userName => ({...comment, posterID: userName})),
            first() // use to complete after one emission to make forkJoin work
          )
        )
        return forkJoin(...getUsers$); // forkJoin them all together for parallel execution
      });
    ).subscribe(data => {
      this.comments = data // now just set the data
    })
    

    【讨论】:

    • 我想我理解逻辑,但它挂起我的代码..好像其中一个操作员没有完成。不过,这是一个很好的起点,谢谢!
    • Firestore observables 可能没有完成......所以这是你想要的行为的一个例子。您想订阅用户名更改还是只获取一次?你想在每次 cmets 发射时获取它们还是只获取一次?
    • 得到它们一次......每次cmets emmits!任何帮助将不胜感激!
    • 在地图之后的内链上应用第一个运算符,答案更新
    猜你喜欢
    • 1970-01-01
    • 2019-01-30
    • 2017-06-17
    • 1970-01-01
    • 2017-07-12
    • 2019-02-18
    • 2018-04-11
    • 2021-11-13
    • 2018-12-16
    相关资源
    最近更新 更多