为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 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 关注
  • 119 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号