jsonangulartypescriptpipeasync-pipe

NG02200: Cannot find a differ supporting object '[object Object]' of type 'object'


Being new to Angular\TS, I want to use Async Pipe to display JSON data . Following is the code with Model Interface.It compiles but gives the error in console and doesn't display anything. I want to use the particular URL given. The error is

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

TS

       customerObs = this.http.get<Customer[]>('https://randomuser.me/api/?format=json');

       constructor(private http: HttpClient) { }

HTML

           <li *ngFor="let customer of customerObs | async">
              {{customer.gender}}
           </li>

Interface

      export interface Customer {gender: string;email: string;}

Solution

  • Looking at the response from the server you will see that it is returning an object and not an array:

    {"results":[{ ... }]}
    

    Option 1

    Option 1 would be to map the response by getting the results property of the object through a pipe() like this:

    import { map } from 'rxjs';
    
    interface Customer { }
    interface Response { results: Customer[] }
    
    customerObs = this.http.get<Response>('https://randomuser.me/api/?format=json')
      .pipe(map(i => i.results))
    

    Option 2

    Option 2 would be to use get the results property directly in the html (along with the generics in the typescript):

    interface Customer { }
    interface Response { results: Customer[] }
    
    customerObs = this.http.get<Response>('https://randomuser.me/api/?format=json');
    
    <ul *ngIf="customerObs | async as response">
      <li *ngFor="let customer of response.results">
        {{customer.gender}}
      </li>
    </ul>