我必须根据第一个API调用的数组响应对对象的数组进行排序。数据应按升序排序。
目前,我有第一个api调用,它返回将在下一个api调用中使用的数组列表。
this.service.fetchStories()
.pipe(
take(1),
).subscribe((res: any) => {
this.storyIds = res;
});
第一个呼叫返回类似的内容。
[0001,0002,0003,0004,0005]
我正在循环浏览故事ID,并将其传递到卡片组件中
<div *ngFor="let id of storyIds | slice: start:end">
<app-cards [id]="id"></app-cards>
</div>
我正在根据我的卡组件中的ID获取第二个api
this.service.fetchStoryItems(this.id)
.pipe(
take(1)
)
.subscribe((res: StoryItem) => {
if (res !== undefined) {
this.data = res;
}
})
第二个api在循环之后返回每个响应
{name: 'John', score: 1}
{name: 'Jane', score: 99}
{name: 'Joe', score: 53}
我被困在这里,想根据第二个api调用返回的分数对项目进行排序。
我在想把每个对象推到一个数组中,然后对新的对象数组进行排序
最好的解决方案是让应用卡变得愚蠢,并将已经提取的故事提供给应用卡。
组件
this.service.fetchStories().pipe(
switchMap(idArray => forkJoin(idArray.map(id => this.service.fetchStoryItems(this.id)))),
map(storyArray => storyArray.sort((a,b) => a.score - b.score)),
take(1),
).subscribe(res => {
this.stories = res;
});
HTML
<div *ngFor="let story of stories | slice: start:end">
<app-cards [story]="story"></app-cards>
</div>
从应用卡中删除HTTP调用
this.data = res.sort( (a,b) => a.score - b.score );
怎么样
您可以修改第二个api调用的返回数据
this.service.fetchStoryItems(this.id)
.pipe(
take(1),
map(response => {
return {...response, id: this.id
})
)
.subscribe((res: StoryItem) => {
if (res !== undefined) {
this.data = res;
console.log(this.data) // should include the id and can be sorted with comparer function
}
})