-1

i created an array in the frontend in angular that had schoolar centers from my database in mongoDB.The problem is when with a ngFor i try to iterate the array of centers.The userService takes the users from my api.

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

    public centers: Center[];

  constructor(
    private _route: ActivatedRoute,
    private _router: Router,
    private _userService: UserService
  ){
    this.user = new User("","","","","","","","","","","");
    this.title = 'Registrate'
  }

  getCenters(){

    this._userService.getCenters().subscribe(

    //Se guardan los centros en un array para poder acceder a ellos desde la plantilla
    response => {
        this.centers = response;
    },
    err => {
      console.log(err);
    }

  )
  }    

    ngOnInit(){

        this.getCenters();

      }
  • 2
    The object you're trying to iterate is not an array – user184994 Oct 20 '18 at 22:29
  • Yes, can you comment the HTML loop and console.log that variable? – José Manuel Blasco Oct 20 '18 at 22:44
  • The `response` is likely an [`HttpResponse`](https://angular.io/api/common/http/HttpResponse) object, not the data your are expecting. Without seeing the `getCenters` method of `UserService`, it's hard to say. – Heretic Monkey Oct 20 '18 at 22:45
  • [Angular: Cannot find a differ supporting object, \[object Object\]](https://stackoverflow.com/questions/35660306/angular-cannot-find-a-differ-supporting-object-object-object) – HDJEMAI Oct 20 '18 at 23:18

2 Answers2

0

In Angular 6, to iterate over an object you can use keyvalue pipe

<div *ngFor="let usr of user | keyvalue">
  {{usr.key}}:{{usr.value}}
</div>
Suryan
  • 701
  • 7
  • 17
  • 1
    The problem is that the array he is trying to iterate is not an array, it is an object as his question says. So he has to know what are the contents of the user variable. – José Manuel Blasco Oct 21 '18 at 03:21
0

Beside keyValue pipe (if you are not using Angular 6+), you can get Object keys as array via

public keys = Object.keys(this.user)

and in template iterate over those keys and get original object value via key matching:

<p *ngFor="let k of keys"> {{user[k]}} </p>

And for sake of completeness, your question is missing HTML snippet. Community doesn't even know over which object you wish ti iterate, I assumed user

Tomas
  • 3,269
  • 3
  • 29
  • 48