有没有更好的方法来更新 ngFor Angular 中的单个项目?

Is there a better way to update single items in ngFor Angular?

什么对我有用:

invoke.directive.ts

export class InvokeDirective {

  @Output() invoke = new EventEmitter();
  ngAfterContentInit() {
    this.invoke.emit(null);
  }

}

posts.component.html

<ul class="list-group">
        <li class="list-group-item" *ngFor="let deal of deals | async, index as i"
        (invoke)="getOwnerData(deal.ownerId)">
          {{ deal.title }} <span class="badge bg-primary" style="color: white; float: right;">{{userNamesArray[i]}}</span>
        </li>
      </ul>

posts.component.html

getOwnerData(userId : string) {
    this.ownerDoc = this.userFirestore.doc<any>('users/' + userId);
    this.dealOwner = this.ownerDoc.valueChanges();

    this.dealOwner.subscribe(res => {
      //console.log(res)
      this.ownerName = res.name;
      this.userNamesArray.push(res.name)

      console.log(this.userNamesArray)
    })
  }

这对我有用,但我只想知道是否有更好的方法。我尝试使用一个值来绑定,但它总是更新为最后一个值,使它们完全相同。非常感谢您的帮助。干杯!

this.deals = this.dealsCollection.snapshotChanges().pipe(
     map(actions => actions.map(a => {
        const data = a.payload.doc.data();
        const id = a.payload.doc.id;
        return { id, ...data };
        })
),
switchMap(ownerDeals =>
   // do this all in parallel (can use concat instead to do one at a time)
      forkJoin(ownerDeals.map(ownerDeal =>
   // create a new observable for each deal
      this.afs.doc<any>(`users/${ownerDeal.ownerId}`).valueChanges().pipe(
   // only take 1 value
    take(1),
   // merge the deal and user info
    map(user => ({
       ...ownerDeal,
       userName: user.name
    }))
     )
   ))
  )
 );

您只需要组合 forkeJoin 和 switchMap,并使用 ownerID 更新用户名和 return 组合数据。所以不需要调用额外的功能。