Search code examples
angularapi

NG02200: Cannot find a differ for object in ngFor '[object Object]'


I'm currently trying to display a comment section on my angular webpage. I'm going this by using my python API. I can successfully console log the results, which are an array. However, when i use ngFor to display the results on my webpage I am returned with the error 'NG02200: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables, such as Arrays.'

This is my ts. file code:

export class CommentComponent {

    replies: any = [];
    comments: any = [];

    constructor(private webService: WebService,
        private route: ActivatedRoute,
        private formBuilder: FormBuilder, 
        public authService : AuthService) {}

       
    ngOnInit() {
        this.comments = this.webService.getComment(this.route.snapshot.params['id'],this.route.snapshot.params['_id'])

HTML:

<div class="container">
    <div class="row">
        <div class="col-sm-12">
            <div class="card bg-light mb-3"
                style = "width: 30rem; margin:auto"
                *ngFor = "let comment of comments | async">
                    <div class="card text-white bg-dark mb-3"
                        > 
                    <div class="card-header">
                        Review by {{ comment.username }}
                        
                    </div>
                    <div class="card-body">
                        {{ comment.comment }}

                        <hr>
                    </div>

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

console logged results: {_id: '63f7ba0deca5ad33c3c18ed0', comment: 'Yeah, this park is dog friendly!', replies: Array(1), username: 'Beth'}


Solution

  • Server response has only an object. Array in JSON looks like

    [{_id: '63f7ba0deca5ad33c3c18ed0', comment: 'Yeah, this park is dog friendly!', replies: Array(1), username: 'Beth'}]

    ([] should be added)

    Check your backend to fix your issue

    And change initializing comments var, to get the error earlier

    //comments: any = []; //components can be an array or anything else
      comments: any[] = [];