亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Angular 的 Observable<Post[]> 中找到具有最高 id 的元素?

如何在 Angular 的 Observable<Post[]> 中找到具有最高 id 的元素?

白衣染霜花 2022-12-18 18:53:22
我剛開始學習 Angular 和 Typescipt,所以遇到了一些麻煩。我正在開發一個顯示照片列表的應用程序,允許我們創建、編輯和刪除現有照片。創建新照片時,我需要找到具有最高 ID 的現有元素,增加 1 并使用新 ID 創建新元素,但我不知道如何使用從 mu getPosts 返回的 Observable<Post[]> 來做到這一點功能。我正在使用來自https://jsonplaceholder.typicode.com/photos的數據。我使用下面的函數獲取所有照片對象export interface Post {  albumId: number,  id: number,  title: string,  url: string,  thumbnailUrl: string}--------------------@Injectable()export class PostsService {  apiUrl = "https://jsonplaceholder.typicode.com/photos";  constructor(private http:HttpClient){  }  getPosts(){    return this.http.get<Post[]>(this.apiUrl);  }}有沒有一種方法可以使用現有函數和 Math.max.apply() 來實現。有人可以幫我嗎?太感謝了。
查看完整描述

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))

}


查看完整回答
反對 回復 2022-12-18
?
qq_笑_17

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;


查看完整回答
反對 回復 2022-12-18
  • 2 回答
  • 0 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號