2

At one point I was successfully iterating over objects in an array in my Angular 2 app using observables. In my client service file I had 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');
}

I then I was subscribing in my component's ngOnInit life cycle hook, like this:

ngOnInit() {
   this.clientService.getByCategory('consulting')
        .subscribe(resRecordsData => this.records = resRecordsData,
        responseRecordsError => this.errorMsg = responseRecordsError);
}

In the component, I also initiated records to be an empty array:

records = [];

And then in my view I was iterating over this array of records like this:

<tr *ngFor="let record of records">

Now the configuration of our data on the api/server has changed. Where I used to be targeting an array, that looked like this:

[
  {
    "id": "someid",
  }
]

... I need to change this to now target an array called "data", that is located WITHIN an object. It looks like this:

{
  "count": 1000,
  "data": [
      {
         "id": "someid",
      }
   ]
}

Simple question that I'm stumped over: How do I target an array WITHIN an object like this? I need to target the array within the object, because that's what *ngFor needs in order to be able to iterate over.

4
  • 3
    try let record of records.data ? or initialize records: this.records = resRecordsData.data ? Commented Apr 10, 2017 at 20:16
  • Good idea. Let me try that. Commented Apr 10, 2017 at 20:18
  • let me know if it works Commented Apr 10, 2017 at 20:19
  • 1
    @floor, that worked. Much appreciated! Commented Apr 10, 2017 at 20:23

1 Answer 1

2

You could try targeting the array in records by:

<tr *ngFor="let record of records.data">

or

you could set records to data in your data retrieval:

this.records = resRecordsData.data
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.