Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular HttpClient map observable array of objects

What is the simplest way to map each object of the result (Rxjs Observable) to an another object when querying an array of objects using angular HttpClient?

I'm currently doing it like below but is there a way to avoid "double mapping"?

In the example the end result needs to be Observable<Entry[]> with the constructor called for each Entry-object:

public getList(): Observable<Entry[]> {
  const url = "/entries/";
  return this.httpClient.get<Entry[]>(url)
    .map((entries: any[]) => entries.map((e) => new Entry(e)));
}
like image 235
Matti Lehtinen Avatar asked Feb 14 '18 19:02

Matti Lehtinen


1 Answers

That's the best way, no shortcut to mapping both the observable and the array, if Entry has any other members than what you get from the api, or if some members need to be type converted (eg. Entry does something to the data in its constructor). If not though, no mapping is needed.

like image 117
funkizer Avatar answered Nov 15 '22 00:11

funkizer