简体   繁体   中英

Angular 7: How to properly this.http.get from a nested response?

I'm doing the Angular 7 tutorial wonder how to properly request a list of items if they are not on the top level, but nested :

Top-Level (works)

[
  { id: 123, name: 'Name 123'},
  { id: 124, name: 'Name 124'},
  // ...
]

Nested (doesn't work)

{
  message: 'x items found.',
  data: [
    { id: 123, name: 'Name 123'},
    { id: 124, name: 'Name 124'},
    // ...
  ]
}

Service

// ...
@Injectable({ providedIn: 'root' })
export class ItemService {
  private apiUrl = 'api/items'; // items are in .data

  constructor(private http: HttpClient) {}

  getItems (): Observable<Item[]> {      
    // Here is the problem:
    return this.http.get<Item[]>(this.apiUrl, {
      pathToItems: 'data' // <- Pseudocode
    });
  }
}

Component

// ...
this.itemService.getItems()
  .subscribe(items => this.items = items);

I could use subscribe() in the service and return the content of .data , but I think there should be a more simple solution. I need to keep the return type (array of Item ).

Any idea?

Thanks in advance!

You can use RxJs filters like map or filter . That's one of the advantages when using RxJs (Observables). You can filter your data before you pass it to your component.

An example:

 return this.http.get(ITEMS_URL).pipe( filter(response => response.filter(data => data.message === "SUCCEEDED")), map(response => response.map(data => data.items)) ); 

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