0

I am getting an error in my console when i am trying to get data of an object within an object and not sure what is the correct mapping to return the array of of data that i need which is results in this case.

here is how my json file looks:

{
"count": 101,
"results": //this is an array[
  object 1, 
  object 2,....
}

My service call:

 getData(){
        return this._http.get('url')
        .map((res:Response) => res.json())
        .catch(this.handleError);
    }

My component file:

getData(){
    this.service.getData().subscribe(
      data => this.results = data,
      error => this.errorMessage = <any>error
    );
  }

html:

<tr *ngFor="let item of results">
   <td><a style="cursor: pointer">{{item.title}}</a></td>
</tr>

2 Answers 2

2

You should access the results array inside the results object, so the ngFor will look like,

<tr *ngFor="let item of results.results">
   <td><a style="cursor: pointer">{{item.title}}</a></td>
</tr>
Sign up to request clarification or add additional context in comments.

7 Comments

i have tried that but i get this console error: ` Error trying to diff '[object Object]'`
did you try the above?
i wasn't sure if i have to change something in my mapping once i get the data to directly get the results object
results contains a list of objects.
change your getData as getData(): Observable<any> {
|
0

You should use async pipe to link observables to template:

<tr *ngFor="let item of (service.getData() | async).results">
   <td><a style="cursor: pointer">{{item.title}}</a></td>
</tr>

I think that your error comes from the fact that results is undefined if the request has not finished yet or if it failed. Using async pipe will remove this issue.

If you still want to handle errors in your component, you can to it like that:

Component:

public getServiceData:Observable<any>{
  return this.service.getData().catch(err => this.errorMessage = <any>err);
}

Html:

<tr *ngFor="let item of (getServiceData() | async).results">
   <td><a style="cursor: pointer">{{item.title}}</a></td>
</tr>

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.