尝试与'[object Object]'进行比较时出错。只允许数组和可迭代-Angular8

时间:2019-07-27 03:02:02

标签: angular angular8

此Angular Code不允许我将JSON文件中的Array内容显示到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>

1 个答案:

答案 0 :(得分:0)

从Im看来,从服务返回的数据不是数组,它是一个对象,其中包含一个数组属性。因此this.apps = { APPLICATIONS: [] },如果要迭代数组,则需要像下面这样访问APPPLICATIONS:

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