使用单个ngFor遍历两个Observable数组时展示值相同该如何解决
错误原因
你原来的写法不符合Angular *ngFor的语法规则:*ngFor仅支持遍历单个数据源,语法中of关键字后只能跟一个待遍历集合,后续所有let 变量 = xxx的声明都是读取ngFor内置的上下文变量(比如index、first、last等),你写的第二个let viewBuffer of scoreCardViewBuffer$ | async不会触发遍历第二个数组,所以viewBuffer实际没有拿到预期的第二个数组的对应项,才会出现两个值显示相同的问题。
解决方案
分两步修改即可:
第一步:TS层组合两个Observable数组
使用RxJS的combineLatest操作符将两个Observable按索引配对,合并为一个新的Observable,保证每一项都包含对应索引的profile和buffer数据:
首先导入依赖:
import { combineLatest } from 'rxjs'; import { map } from 'rxjs/operators';
声明组合后的Observable:
combinedScoreCards$: Observable<{ profile: ScoreCardView, buffer: ScoreCardView }[]>;
在两个原始Observable赋值后完成组合:
this.combinedScoreCards$ = combineLatest([ this.scoreCardViewProfile$, this.scoreCardViewBuffer$ ]).pipe( // 按索引配对两个数组的元素 map(([profileList, bufferList]) => profileList.map((profileItem, index) => ({ profile: profileItem, buffer: bufferList[index] })) ) );
第二步:修改模板遍历组合后的数据源
外层*ngFor直接遍历组合后的Observable,内层通过索引获取buffer对应的子项即可,为了避免多次调用async管道,建议外层用ng-container先缓存异步结果:
<ng-container *ngIf="combinedScoreCards$ | async as combinedList"> <div *ngFor="let item of combinedList; let i = index"> <div class="row"> <p class="pl-5 font-weight-boldest font-size-lg"> {{item.profile.scoreCardCategoryName}} </p> <div class="col-12"> <mat-divider></mat-divider> <div class="row"> <div *ngFor="let detailsProfile of item.profile.listOfQuestionDto; let j=index" class="col-6"> <div class="row pt-5 pb-5"> <div class="col-12 text-muted font-weight-bolder"> <p align="left">{{detailsProfile.question}}</p> </div> <div class="row pl-4"> <div class="col-12 font-weight-bolder"> <p>profile:{{detailsProfile.configItemName}}</p> <!-- 直接通过索引j取buffer对应位置的子项 --> <p>buffer: {{item.buffer.listOfQuestionDto[j].configItemName}}</p> </div> </div> </div> </div> </div> </div> </div> <div class="row pl-4" *ngIf="i === combinedList.length -1"> <div class="col-12 pl-0 text-muted font-weight-bolder border-bottom"> <p>Status</p> </div> <div class="col-12 pl-0 font-weight-bolder"> <p class="pt-4">{{item.profile.status}}</p> </div> </div> </div> </ng-container>
内容的提问来源于stack exchange,提问作者Black Swan
相关产品推荐
相关产品推荐

