Angular 嵌套订阅代码未按预期工作

Angular nested subscribe code not working as expected

我的任务包括 2 个步骤。第一步是从 firestore 中检索一些 id 数据。其次是根据第一步检索到的数据检索名称数据。所以我为每个步骤使用了 1 个订阅。在我正在执行 console.log() 的代码中,出现了正确的结果,但是当网页加载时,下拉列表为空。

this.MessagingService.recieveGetClient().subscribe(idData => {
  this.dropdownList = [];
  idData.map((id: string, i: number) => {
    this.VehicleService.getOwnerInfo(id).subscribe(namedata => {
      this.dropdownList.push({ item_id: `${i}`, doc_id: namedata['username'] });
      console.log("this.dropdownList:",this.dropdownList);
    });
  });
});

下面是 HTML 代码。如果我摆脱第二个订阅并使用 id 而不是 dropdownList 的用户名,那么它就可以工作。但是我需要使用用户名。

<ng-multiselect-dropdown
    [settings]="dropdownSettings"
    [placeholder]="'Send Message to...'"
    [data]="dropdownList"
    [(ngModel)]="selectedItems"
    (onSelect)="onItemSelect()"
    (onSelectAll)="onSelectAll($event)"
    (onDeSelect)="onItemDeSelect()"
    (onDeSelectAll)="onDeSelectAll()"
>
</ng-multiselect-dropdown>

由于它是多个订阅和映射数据,因此最好使用一个可观察对象来通过 switchMap 传递不同的源,如下所示:

this.dropdownList$  = this.MessagingService.receiveGetClient()
.pipe(switchMap(id => this.VehicleService.getOwnerInfo(id).pipe(map(nameData => ({id, doc_id: nameData.username})))
));

在模板中,您可以使用异步管道来解包值

[data]="dropdownList$ | async"

请注意,由于异步管道会订阅,因此您无需在组件中手动订阅或担心取消订阅。

希望对您有所帮助!