我有一个对象数组,我可以从API一次得到它,然后像这样在.component.html
中显示它们:
<div *ngFor="let obj of ObjectArray">
<div>{{obj.name}}</div>
</div>
我需要对每个对象进行第二次API调用,在其中我将填充第二个对象数组,并将其显示在obj.name
下,而我试图这样做:
<div *ngFor="let obj of ObjectArray">
<div data-dummy="{{populateAnotherObjectArray(obj.id)}}"></div>
<div>{{obj.name}}</div>
<div *ngFor="let anotherObj of AnotherObjArray">
{{anotherObj.name}}
</div>
</div>
[populateAnotherObjectArray(obj.id)
是component.ts
文件中的函数,我在其中填充AnotherObjArray。
现在我只能无休止地调用第二个API。
我尝试使用Directive和EventEmitter,但那里什么也没得到。
有没有简单的方法可以做到这一点?
[尽量避免在指令和内插中调用函数。如果您不控制变更检测策略,那么它们将被调用太多次。您可以在显示数据之前在控制器中触发呼叫。尝试以下操作
import { forkJoin, of } from 'rxjs';
import { catchError, switchMap } from 'rxjs/operators';
ngOnInit() {
this.apiService.getObjectArray().pipe(
switchMap(arr1 => {
this.ObjectArray = arr1;
return forkJoin(arr1.map(item => this.apiService.getAnotherObjArray(item['id'])));
}),
catchError(err1 => {
// handle error
return of(err1);
})
).subscribe(
arr2 => {
this.AnotherObjArray = arr2;
},
err2 => {
// handle error
}
);
}
这里AnotherObjArray
实际上是对象数组的数组。