I encountered a situation where I was successfully looping through objects in an array within my Angular 2 application using observables. In the client service file, my code looked like this:
getByCategory(category: string) {
const q = encodeURIComponent(category);
return this.http.get
(`https://api.someurl.com/${this.ver}/clients/category/${q}?apikey=${this.key}`)
.map((response: Response) => response.json())
.catch(this.stageErrorsHandler);
}
stageErrorsHandler(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
Next, I subscribed to this in the ngOnInit life cycle hook of my component:
ngOnInit() {
this.clientService.getByCategory('consulting')
.subscribe(resRecordsData => this.records = resRecordsData,
responseRecordsError => this.errorMsg = responseRecordsError);
}
In the component, I initialized the records as an empty array:
records = [];
Then, in my view, I looped through this array of records like this:
<tr *ngFor="let record of records">
Now, the configuration of our data on the api/server has changed. Previously, I was targeting an array structure like this:
[
{
"id": "someid",
}
]
... but now I need to target an array called "data" within an object. The new structure looks like this:
{
"count": 1000,
"data": [
{
"id": "someid",
}
]
}
I have a simple question that is puzzling me: How can I target an array within an object like this? It's necessary to target the array within the object for *ngFor to iterate over it.