Mellville
Mellville

Reputation: 1097

Unable to loop through all elements in an array of objects; ngFor or iteration in the component only gives me the first element

This may sound strange, at least I find it strange or something very basic is escaping me: After mapping the API response, I manage to store an array of 10 objects into a variable. the data looks like this:enter image description here

This is the method that gets the data. The log shown comes from this.finalPhraseResults:

receivedPhrase(value){
    this.guardian.searchByPhrase(value)
    .subscribe(result=>{
      this.phraseResults=Array.of(result).map(x=>x['response'])
      this.finalPhraseResults = this.phraseResults.map(x=>x['results']);
     console.log(this.finalPhraseResults)
    })
  }

And the HTML

<ul class="list-group" *ngFor="let p of finalPhraseResults">
      <li class="list-group-item">
        {{p.type}}
      </li>
      <li class="list-group-item">
        {{p.sectionId}}
      </li>
      <li class="list-group-item">
        {{p.sectionName}}
      </li>
      <li class="list-group-item">
        {{p.webPublicationDate}}
      </li>
      <li class="list-group-item">
        <button mat-raised-button color="primary" (click)="goToPhraseExternal(p.id)">Go to article</button>
      </li>
    </ul>

The result is a blank page. But if I write something like this:

this.finalPhraseResults = this.phraseResults.map(x=>x['results'][0]);

I get data rendered but only from the first object, obviously. So I'm kind of lost here. Can someone explain to me what is happening?

EDIT The Original response @Michael D enter image description here

Upvotes: 1

Views: 713

Answers (3)

Dany Mathew
Dany Mathew

Reputation: 11

You can create a new variable to store final Phrase Results and ngFor* with that array. New class should be defined with all the properties.

public class FinalPhraseResult{
public string id;
public string type;
public string sectionId;
}

now in your ts file you can declare a variable public finalPhraseResult:FinalPhraseResult[] = [];

In your subscribe you can assign value to this new array this.finalPhraseResult = this.phraseResults.map(x=>x['results'])[0];

This is the important part, as the result return is also an array,you have to select the from index 0.

In the html template you can now use

<ul class="list-group" *ngFor="let p of finalPhraseResult">
  ...
</ul>

Upvotes: 0

ng-hobby
ng-hobby

Reputation: 2199

It seems that you have an array of array. try this:

this.phraseResults=Array.of(result).map(x=>x['response'])
this.finalPhraseResults = this.phraseResults[0]  

Upvotes: 3

Barremian
Barremian

Reputation: 31135

The variable is an array of an array. The quick fix would be

Controller

this.finalPhraseResults = this.phraseResults.map(x=>x['results']);

Template

<ul class="list-group" *ngFor="let p of finalPhraseResults[0]">
  ...
</ul>

Upvotes: 1

Related Questions