Search code examples
angularhttphttpclientangular-httpclient

Getting "Cannot read property 'of' of undefined" using angular 8, and httpclient


I have configured my project with new httpclient using following service. AppModule.ts is setup correctly

getAllLocosByID(locoID: string) {
    return this.http.get<Search[]>(`${environment.apiUrl.searchbylocoid}/${locoID}`);
}

Also Search is set to be

export class Search {
    input: string;
    warningMessages: String[];
    errorMessages: String[];
    numFound: number;
    results: String[];
    APP_CODE: string;
}

on my component I have

logoSearchResults: Search[];
constructor(private data: DataAccessService) { }    
getLocmotives() {
    this.data.getAllLocosByID('A1').subscribe((res: Search[]) => {
    // console.log(Array.of(res));
    // console.log(typeof (response));
    // this.logoSearchResults = res;
    this.logoSearchResults = { ...res };
    console.log(this.logoSearchResults);
 },
  error => {
    console.log("error");
  })
}

which gives me following on the browser console. Based on httpclient documents returning response is already an observable json which I am forming it to a Search[]

{input: "A1", warningMessages: Array(0), errorMessages: Array(0), numFound: 241, results: Array(3), …}

So far, so good!. but lets put it on HTML part, and show it to the end user

I put a button on the HTML that works with click

<button class="btn btn-primary" (click)="getLocmotives()">
   Give me answer
</button>
{{ logoSearchResults }}

This is what I get on screen from {{ logoSearchResults }}

[object object]

by updating HTML codes to loop through this array to

<ul class="list-group">
  {{ logoSearchResults }}
  <li class="list-group-item" *ngFor="let result of logoSearchResults">
     {{ result }}
  </li>
</ul>

I am getting following error

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

By updating HTML codes to

<ul class="list-group">
 {{ logoSearchResults }}
 <li class="list-group-item" *ngFor="let result of Array.of(logoSearchResults)">
    {{ result }}
 </li>

I am getting following error

ERROR TypeError: Cannot read property 'of' of undefined

What should I do in HTML or angular part to be able to show my data on scree?


Solution

  • you should add an array to ngfor: *ngFor="let result of logoSearchResults.results"