Angular / Typescript找不到类型为“对象”的其他支持对象“ [对象对象]”。 NgFor仅支持绑定到数组等Iterables

时间:2020-10-16 14:53:43

标签: angular typescript

我正在使用角度

尝试调用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;
}

使用此t.s组件

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收集的信息,我知道我可能需要将其转换为另一种数据类型,但是我不确定如何执行此操作。

1 个答案:

答案 0 :(得分:2)

您应该尝试:

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

代替

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

因为数据是实际数据,而不是SubscriptionObservable。 顺便说一句,您的ngOnInit没有理由要有return语句。

打开

users$: User[];

进入

users$: Observable<User[]>;

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

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