首页 > 解决方案 > 尝试区分“[object Object]”时出错。只允许使用数组和可迭代对象 - Angular8

问题描述

此 Angular 代码不允许我将 JSON 文件中的数组内容显示到 HTML 上。控制台中的错误显示“尝试区分'[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>

标签: angularangular8

解决方案


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

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

推荐阅读