2 回答

TA贡献1785条经验 获得超4个赞
让我们做一个简单的函数返回一个最大 id 的帖子(这不是真的有必要,但会让代码更简洁):
function findMax(list: Post[]): Post | undefined {
if (!list.length) return undefined;
return list.reduce((max, post) => post.id > max.id ? post : max )
}
现在让我们使用 pipe() 来转换使用我们函数的 http 调用的结果:
getMaxPost(): Observable<Post | undefined> {
return this.http.get<Post[]>(this.apiUrl).pipe(map(findMax));
}
如果您真的不关心带有 max id 的帖子并且只需要 max id 本身,那么您可以findMaxId(list)实现类似于 @Harmandeep Singh Kalsi 建议的内容:
findMaxId(list) {
return Math.max(...list.map(post => post.id))
}

TA贡献1818条经验 获得超7个赞
您必须有一些组件,您可以在其中订阅 API 的结果,例如
export class TestingComponent{
maxId: number;
constructor(postService: PostsService){}
getPosts(){
this.postService.getPosts().subscribe(data => {
this.maxId=Math.max.apply(Math,data.map(obj => obj.id));
})
}
}
我能想到的其他方法是首先根据 id 对数组进行排序并获取最后一个 id ,这将是最大 id 。
this.posts = this.posts.sort((a,b) => a-b);
this.maxId = this.posts[this.posts.length-1].id;
添加回答
举报