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

我刚开始学习 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() 来实现。有人可以帮我吗?太感谢了。


白衣染霜花
浏览 120回答 2
2回答

九州编程

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

qq_笑_17

您必须有一些组件,您可以在其中订阅 API 的结果,例如export class TestingComponent{&nbsp; &nbsp; maxId: number;&nbsp; &nbsp; constructor(postService: PostsService){}&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; getPosts(){&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;this.postService.getPosts().subscribe(data => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.maxId=Math.max.apply(Math,data.map(obj => obj.id));&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;})&nbsp; &nbsp; }}我能想到的其他方法是首先根据 id 对数组进行排序并获取最后一个 id ,这将是最大 id 。this.posts = this.posts.sort((a,b) => a-b);this.maxId = this.posts[this.posts.length-1].id;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript