首页 > 解决方案 > Angular/Typescript 找不到“object”类型的不同支持对象“[object Object]”。NgFor 仅支持绑定到 Iterables,例如 Arrays

问题描述

我正在使用角度

尝试调用 api 并从中检索数据,但它会引发此错误。

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

我的服务看起来像

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { User } from '../Models/user.model';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  apiUrl = 'myurl is in here but i cannot show'

  constructor(private _http: HttpClient) { }

  getUsers(){
    return this._http.get<User[]>(this.apiUrl);
  }
}


用户模型看起来像

export class User {
    alertId: any;
    itemId: string;
    title: string;
    description: string;
    categoryId: any;
    riskId: any;
    sourceId: any;
    startDate: any;
    endDate: any;
    link: string;
    countryId: any;
    countries: string;
    keywordMatches: string;
    keywordsMatched: 0;
    createdDate: any;
    createdBy: any;
    isDeleted: true;
    deletedDate: any;
    deletedBy: any;
    latitude: 0;
    longitude: 0;
    notes: string;
    customerId: any;
    formattedAddress: any;
    firstname: any;
    surname: any;
    email: string;
    phone: string;
    smsEnabled: true;
    customerName: string;
    homeCountryId: any;
    travellerTagId: 0;
}

这个 ts 组件使用它

import { Component, OnInit } from '@angular/core';
import { User } from 'src/app/Models/user.model';
import { DataService } from 'src/app/Services/data.service';
 
 

@Component({
  selector: 'app-side-nav-alerts',
  templateUrl: './side-nav-alerts.component.html',
  styleUrls: ['./side-nav-alerts.component.css']
})
export class SideNavAlertsComponent implements OnInit {
users$: User[];
  constructor( private dataService : DataService) { }



  ngOnInit(){
    return this.dataService.getUsers()
    .subscribe(data => this.users$ = data)
  
  }

}


HTML

<div *ngFor = 'let user of users$' style="text-align: center;">
    <h2>{{user.name}}</h2>
    </div>

关于如何使用它来循环的任何想法?我基本上只是想遍历它并显示从 api 收集的信息我知道也许我需要将它转换为另一种数据类型,但我不确定如何执行此操作。

标签: angulartypescript

解决方案


你应该试试:

ngOnInit(){
  this.users$ = this.dataService.getUsers()  
}

代替

ngOnInit(){
  return this.dataService.getUsers()
  .subscribe(data => this.users$ = data)
}

由于数据是实际数据而不是Subscription相应的数据。Observable. 顺便说一句,您没有理由ngOnInit有退货声明。

转动

users$: User[];

进入

users$: Observable<User[]>;

在您的 html 中,您需要像这样使用异步管道:

*ngFor = 'let user of (users$ | async)' style="text-align: center;"

推荐阅读