FarFarAway
FarFarAway

Reputation: 1115

Data are not displayed althought the request is valid

I have a microservice and an angular web page that looks like

export class FilpComponent implements OnInit {
  flipped = false;
  word: MetaWord;

  flipIt() {
    this.flipped = !this.flipped;
  }

  constructor(private breakpointObserver: BreakpointObserver, private  metaWordService: MetaWordService) {
  }

  ngOnInit() {
    this.metaWordService.read('laufen').subscribe(
      (data: MetaWord) => {
        this.word = data;
// this outputs undefined
        console.log(this.word.word);
      });
  }

  getSences(): Sens[] {
    return this.word.senses;
  }
}

and the Template looks like

<ng-container *ngIf="word !== undefined">
  <div>{{word.word}}</div>
</ng-container>

the request is sent properly and I can display the Data in Chrome DevTools. But the output of the subscribe is undefined.

This is the Output of console.log(data) or console.log(word) enter image description here

UPDATE: Thanks to Nicholas K it does work now but I have the same problem here

the method getWords() return a populated object of type word. Object word would now have different senses. I want to show the different senses as divs as follows:

<div *ngFor="let word of getWords()">
  <div id="player" class="player" [class.voted]="flipped">
    <div class="front">
      <div class="grid-container">
        <h1 class="mat-h1">Dashboard</h1>
        <h1 class="mat-h1">{{word.word}}</h1>
        <div *ngFor="let example of word.senses">
          <div> here is an example of the word : {{example.sense}}</div>
        </div>

      </div>
    </div>
  </div>
</div>

the word object is populated with data, but I expect to see multiple divs

The code of read in backend service is

return this.httpClient.get<MetaWord[]>(`${environment.words.baseUrl}/${term}`);

when I wirte a test method like this

  public print(){
    this.wordList.forEach(word=>{
      console.log(word.senses.length);
    })
  }

and call it after the data has been called from the backend service, then i get the error

TypeError: Cannot read property 'length' of undefined

It is somehow not correctly parsing the data to my object

Upvotes: 1

Views: 61

Answers (1)

Nicholas K
Nicholas K

Reputation: 15443

data is an array, you need to access an index first to reach the desired object.

For eg:

console.log(this.data[0].word);


Make the following change:

 ngOnInit() {
    this.metaWordService.read('laufen').subscribe(
      (data: MetaWord[]) => {
        // access via an index
        console.log(this.data[0].word);
      });
 }

assuming that your model MetaWord has been defined according to the response present in the question.

Upvotes: 2

Related Questions