Search code examples
angulartypescriptrxjsngfor

Angular 12 - returns loop


I'm getting data from api as object. I'm trying to use in component.html with ngFor but I'm getting this error

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

So my object like this:

{id: 9, name: 'test', username: 'testmg', email: '[email protected]', email_verified_at: null, …}

How can I solve this?

profile.component.ts

  username:any
  playerData:any

  constructor(private dataService: DataService,private router: ActivatedRoute) { }

  ngOnInit(): void {
    this.username = this.router.snapshot.params.username
    this.getOne()
  }


  getOne(){
    this.dataService.getProfile(this.username).subscribe(res=>{
      this.playerData = res
    })
  }

profile.component.html

 <div *ngFor="let item of playerData">
     {{item}}
 </div>

Solution

  • Wrap object in the array using RxJs map before assigning response to this.playerData, No change is needed in the template.

    this.dataService.getProfile(this.username).pipe(
     map(resp => [resp])
    ).subscribe(res=>{
      this.playerData = res;
    }
    

    Some code optimization:

    Declare playerData as

    playerData$: Observable<any[]>;
    

    Bind API response to playerData$

    this.playerData$ = this.dataService.getProfile(this.username).pipe(
        map(resp => [resp])
    );
    

    In template use AsyncPipe which will subscribe and unsubscribe for us:

    <div *ngFor="let item of playerData$ | async">
        {{item}}
    </div>
    

    This way you do not need to take care of subscribing and unsubscribing to Observable.

    Imports used

    import { map } from 'rxjs/operators';
    import { Observable } from 'rxjs';