【发布时间】: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)