1
votes

I am getting this error:

CommunityUpdateComponent.html:1

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

Even when I follow this solution: *ngFor="let userOption of users?.id

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

<div class="form-group">
    <label class="form-control-label" jhiTranslate="jhipsterPress07App.community.user" for="field_user">User</label>
     <!--  <select class="form-control" id="field_user" name="user" [(ngModel)]="community.userId"  required>  -
    <select class="form-control" id="field_user" name="user" [(ngModel)]="community.userId"  required> <option *ngIf="!editForm.value.user" [ngValue]="null" selected></option>
       <option [ngValue]="userOption.id" *ngFor="let userOption of users?.id; trackBy: trackUserById">{{userOption.id}}</option>
    </select>
</div>

Here is my ts file where I put the result of the request in the array: this.users = res.body; users: IUser[];

import { Component, OnInit, ElementRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import * as moment from 'moment';
import { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants';
import { JhiAlertService, JhiDataUtils } from 'ng-jhipster';

import { ICommunity } from 'app/shared/model/community.model';
import { CommunityService } from './community.service';
import { IUser, UserService } from 'app/core';
import { IInterest } from 'app/shared/model/interest.model';
import { InterestService } from 'app/entities/interest';
import { IActivity } from 'app/shared/model/activity.model';
import { ActivityService } from 'app/entities/activity';
import { ICeleb } from 'app/shared/model/celeb.model';
import { CelebService } from 'app/entities/celeb';

import { Principal } from 'app/core';

@Component({
selector: 'jhi-community-update',
templateUrl: './community-update.component.html'
})
export class CommunityUpdateComponent implements OnInit {
private _community: ICommunity;
isSaving: boolean;

users: IUser[];

interests: IInterest[];

activities: IActivity[];

celebs: ICeleb[];
creationDate: string;
currentAccount: any;

constructor(
    private dataUtils: JhiDataUtils,
    private jhiAlertService: JhiAlertService,
    private communityService: CommunityService,
    private userService: UserService,
    private interestService: InterestService,
    private activityService: ActivityService,
    private celebService: CelebService,
    private elementRef: ElementRef,
    private principal: Principal,
    private activatedRoute: ActivatedRoute
) {}

ngOnInit() {
    this.isSaving = false;
    this.activatedRoute.data.subscribe(({ community }) => {
        this.community = community;
    });
    console.log('1.-Testing: Printing this.isSaving = false', 
    this.interestService.query().subscribe(
        (res: HttpResponse<IInterest[]>) => {
            this.interests = res.body;
        },
        (res: HttpErrorResponse) => this.onError(res.message)
    );
    console.log('2.- Bring the activities');
    this.activityService.query().subscribe(
        (res: HttpResponse<IActivity[]>) => {
            this.activities = res.body;
        },
        (res: HttpErrorResponse) => this.onError(res.message)
    );
    this.celebService.query().subscribe(
        (res: HttpResponse<ICeleb[]>) => {
            this.celebs = res.body;
        },
        (res: HttpErrorResponse) => this.onError(res.message)
    );
}

userServiceId(currentAccount) {
    this.userService
       .query2(this.currentAccount.login)
        .subscribe(
                (res: HttpResponse<IUser[]>) => {
                    this.users = res.body;
                    console.log('4.- Printing the res.body: ', res.body);
                },
                (res: HttpErrorResponse) => this.onError(res.message)
        );
    console.log('5.- Printing the this.currentAccount.id', this.currentAccount.id);
}

byteSize(field) {
    return this.dataUtils.byteSize(field);
}

openFile(contentType, field) {
    return this.dataUtils.openFile(contentType, field);
}

setFileData(event, entity, field, isImage) {
    this.dataUtils.setFileData(event, entity, field, isImage);
}

clearInputImage(field: string, fieldContentType: string, idInput: string) {
    this.dataUtils.clearInputImage(this.community, this.elementRef, field, fieldContentType, idInput);
}

previousState() {
    window.history.back();
}

save() {
    this.isSaving = true;
    this.community.creationDate = moment(this.creationDate, DATE_TIME_FORMAT);
    if (this.community.id !== undefined) {
        this.subscribeToSaveResponse(this.communityService.update(this.community));
    } else {
        this.subscribeToSaveResponse(this.communityService.create(this.community));
    }
}

private subscribeToSaveResponse(result: Observable<HttpResponse<ICommunity>>) {
    result.subscribe((res: HttpResponse<ICommunity>) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError());
}

private onSaveSuccess2(result) {
    this.isSaving = false;
}

private onSaveSuccess() {
    this.isSaving = false;
    this.previousState();
}

private onSaveError() {
    this.isSaving = false;
}

private onError(errorMessage: string) {
    this.jhiAlertService.error(errorMessage, null, null);
}

trackUserById(index: number, item: IUser) {
    return item.id;
}

trackInterestById(index: number, item: IInterest) {
    return item.id;
}

trackActivityById(index: number, item: IActivity) {
    return item.id;
}

trackCelebById(index: number, item: ICeleb) {
    return item.id;
}

getSelected(selectedVals: Array<any>, option: any) {
    if (selectedVals) {
        for (let i = 0; i < selectedVals.length; i++) {
            if (option.id === selectedVals[i].id) {
                return selectedVals[i];
            }
        }
    }
    return option;
}
get community() {
    return this._community;
}

set community(community: ICommunity) {
    this._community = community;
    this.creationDate = moment(community.creationDate).format(DATE_TIME_FORMAT);
}
}

When I use this alternate code which does not filter, it works because it fetches a bunch of User, but when an Array of 1, was not an Array?

this.userService.query().subscribe(
    (res: HttpResponse<IUser[]>) => {
        this.users = res.body;
        console.log('4.- Printing the res.body: ', res.body);
    },
    (res: HttpErrorResponse) => this.onError(res.message)
);

Thanks

2
You're trying to loop through users?.id. So, unless users?.id is an array (or some other iterable), what you are doing wont work. Should you be looping through users instead?R. Richards
Thanks for your help, but it does not work: CommunityUpdateComponent.html:1 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays. Your solution was my first try before I saw the solution I pasted at the top which used the *ngFor="let userOption of users?.idMike

2 Answers

1
votes

You are trying to iterate an object but you can only iterate arrays.

In JavaScript its worth knowing that an array is an object. If you want to check whether an object is a normal object or an array use Array.isArray(varToCheck)

Anyway, you can iterate object properties using the new pipe introduced in ng6.1

<div *ngFor="let item of object | keyvalue">
  {{item.key}}:{{item.value}}
</div>

https://angular.io/api/common/KeyValuePipe

0
votes

You are basically doing a for on an unindexed sub object. So you are trying to hit users[0].id but instead you are doing users.id which is undefined. Then in the for you are doing a userOption.id which is basically a user.id.id which throws the error. Also, if you aren't reordering/updating the list then you don't need the trackby. This html should work

<div class="form-group">
  <label class="form-control-label" jhiTranslate="jhipsterPress07App.community.user" for="field_user">User</label>
  <select class="form-control" id="field_user" name="user" [(ngModel)]="community.userId"  required> 
    <option *ngIf="!editForm.value.user" [ngValue]="null" selected></option>
    <option [ngValue]="userOption.id" *ngFor="let userOption of users">{{userOption.id}}</option>
 </select>
</div>