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;
添加回答
舉報