【问题标题】:Error trying to diff '[object Object]'. Only arrays and iterables are allowed - Angular8尝试区分“[object Object]”时出错。只允许使用数组和可迭代对象 - Angular8
【发布时间】:2019-07-27 03:02:02
【问题描述】:

此 Angular 代码不允许我将 JSON 文件中的数组内容显示到 HTML 上。控制台报错显示“Error trying to diff '[object Object]'”

此代码在我本地运行的 Angular 8 上运行。我尝试了许多不同的获取数据的方法以及在 HTML 中显示的不同方式,但似乎都不起作用

JSON File 
{...} represent a string
{
  "APPLICATIONS": [
    {
      "APP_ID": 1,
      "APP_NAME": "...",
      "APP_SHORT_NAME": "...",
    },...


TS

export class Application {
    APP_ID: number;
    APP_NAME: string;
    APP_SHORT_NAME: string;
}


Service.TS

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Application } from '../intdets';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class IntdetsService {

  private _url = "/assets/IntDet.json";
  constructor(private http: HttpClient) { }

  getIntdets(): Observable<Application[]> {
    return this.http.get<Application[]>(this._url);
  }
}


Component.TS 

import { Component, OnInit } from '@angular/core';
import { IntdetsService } from '../service/intdets.service';

@Component({
  selector: 'app-intdets',
  templateUrl: './intdets.component.html',
  styleUrls: ['./intdets.component.css']
})
export class IntdetsComponent implements OnInit {

  public apps = [];

  constructor(private _intdetsService: IntdetsService) { }

  ngOnInit() {
    this._intdetsService.getIntdets()
        .subscribe(data => this.apps = data);
  }

}

HTML

<ul *ngFor = "let app of apps">
  <li>{{app.APP_ID}}</li> //Test code to only print one element
</ul>

【问题讨论】:

  • 您是否尝试在没有 ngFor 的情况下仅使用 console.log(apps)

标签: angular angular8


【解决方案1】:

据我所见,从服务返回的数据不是数组,它是一个包含数组属性的对象。所以this.apps = { APPLICATIONS: [] },如果你想迭代数组,你需要像这样访问APPLICATIONS:

<ul *ngFor = "let app of apps.APPLICATIONS">
  <li>{{app.APP_ID}}</li> //Test code to only print one element
</ul>

【讨论】:

    猜你喜欢
    • 2018-09-14
    • 2020-08-15
    • 2021-12-21
    • 2018-11-25
    • 2021-10-22
    • 2020-05-27
    • 2018-07-15
    • 2021-01-09
    相关资源
    最近更新 更多