简体   繁体   中英

How can I find the element with the highest id in my Observable<Post[]> in Angular?

I am new at learning Angular and Typescipt, so I have a bit of trouble. I am working on an app that displays list of photos, allows us to create, edit and delete alredy existing photos. When creating new photo, I need to find the already existing element with the highest id, increase by 1 and create the new element with the new ID, but I dont know how to do that using Observable<Post[]> returned from mu getPosts function. I am using data from https://jsonplaceholder.typicode.com/photos . I get all photos objects using the function below

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

Is there a way to do it using the existing function and Math.max.apply(). Can somebody help me? Thank you so much.

Let's make a simple function returns an post with max id (it's not really necessary, but will make code a bit cleaner):

function findMax(list: Post[]): Post | undefined {
    if (!list.length) return undefined;
    return list.reduce((max, post) => post.id > max.id ? post : max )
}

Now let's use pipe() to transform the result from the http call using our function:

getMaxPost(): Observable<Post | undefined> {
  return this.http.get<Post[]>(this.apiUrl).pipe(map(findMax));
}

If you don't really care about the post with max id and only need max id itself, you could have findMaxId(list) implemented similar to what @Harmandeep Singh Kalsi suggested:

findMaxId(list) {
  return Math.max(...list.map(post => post.id))
}

You must have some component where you are subscribing the result of the API like

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

Other way I could think of is first sort the array based on id and get last id, which will the max id.

this.posts = this.posts.sort((a,b) => a-b);
this.maxId = this.posts[this.posts.length-1].id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM