代码之家  ›  专栏  ›  技术社区  ›  Mike

错误:找不到类型为“object”的不同支持对象“[object]”,但我使用的是一个数组。解决方案?

  •  0
  • Mike  · 技术社区  · 6 年前

    我得到这个错误:

    通信UnityUpdate组件.html:1

    错误:找不到不同的支持对象“[object]” 类型为“object”。NgFor只支持绑定到Iterables,例如 数组。

    即使我遵循这个解决方案: *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>
    

    这是我的ts文件,我将请求的结果放入数组中:此.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);
    }
    }
    

    当我使用这个不过滤的替代代码时,它工作是因为它获取了一堆用户,但是当一个1的数组不是一个数组时?

    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)
    );
    

    2 回复  |  直到 5 年前
        1
  •  0
  •   rhavelka    6 年前

    您基本上是在未建立索引的子对象上执行for。所以你想打我 users[0].id users.id 这是未定义的。那么在为你做一个 userOption.id 基本上是一个 user.id.id

    <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>
    
        2
  •  1
  •   danday74    6 年前

    您试图迭代对象,但只能迭代数组。

    在JavaScript中,数组是一个对象是值得知道的。如果要检查对象是普通对象还是数组,请使用 Array.isArray(varToCheck)

    无论如何,您可以使用ng6.1中引入的新管道来迭代对象属性

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

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