angular - 尝试区分“[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>
解决方案
从我所看到的,从服务返回的数据不是一个数组,它是一个包含数组属性的对象。因此this.apps = { APPLICATIONS: [] }
,如果您想迭代数组,您需要像这样访问 APPLICATIONS:
<ul *ngFor = "let app of apps.APPLICATIONS">
<li>{{app.APP_ID}}</li> //Test code to only print one element
</ul>
推荐阅读
- python - Django 可以用 CreateView 设计 AJAX 字段过滤器吗?
- html - 填写 web 表单,带下拉菜单的动态表
- .htaccess - 当我尝试将 htaccess 转换为 nginx 文件时出现问题,触发下载
- javascript - 如何将\xe2\x80\x99等字符转换为html字符串中的普通撇号
- python - 在工作目录中创建多个文件夹
- c# - C# 窗口窗体中的退格
- macros - 为什么“#define OPERATION(op)x op = value”宏在g ++中给我“错误:'='令牌之前的预期主表达式”?
- javascript - PHP/Javascript 切换功能问题
- kubernetes - Rancher - 如何公开我的服务?
- c# - 寻找一种使用打开 xml 将可折叠功能应用于 word 文档中的标题的方法