Extract part of Observable into a new observable

Viewed 75

I have the following interfaces

export interface Student {
  id: number;
  firstname: string;
  lastname: string;
  birthdate?: Date;
  created_at: Date;
  updated_at: Date;
  contacts: Contact[];
  contacts_attributes: Contact[];
}

export interface StudentsData {
  students: Student[];
  count: number;
  offset: number;
  limit: number;
}

And a service, that returns an Observable<StudentsData>

getStudentsData(orderBy?: string, orderDirection = 'asc'): Observable<StudentsData> {
   return this.http.get<StudentsData>('/api/students', {params})
}

Is it possible to use the Observable<StudentsData> and create an Observable<Stundet[]>?

2 Answers

You're looking for the rxjs operator map:

this.getStudentsData(....).pipe( map(studentsData => studentsData.students) )

Pluck

Pluck is a little more concise when all you want to do is extract a part of the data:

this.getStudentsData(/* Your params... */)
  .pipe(pluck('students'))
Related