我正在尝试从本地 json 文件中读取一些测试数据,并将格式正确的数据输出到文本区域中。现在虽然它只是输出 [object Object]。我将如何获得它以便输出:
Id: theIdGoesHere
标题:theTitleGoesHere
step.service.ts 用于调用json数据的服务
public getJson(): Observable<any>{
return this.http.get('/assets/jsonData/MyJson.json')
.map(response => response.json());
}
MyJson.json
{
"data":[
{
"id": 1,
"title":"Test1"
},
{
"id": 2,
"title":"Test2"
}
]
}
main.componenet.ts
private testVar: any;
test(){
this.stepService.getJson().subscribe(data => (this.testVar = data));
}
anothermethod(){
this.test();
this.mainStepText = this.testVar; //mainStepText binded to textarea with [(ngModel)]="mainStepText"
}
get mainStepText2() { //Rebinded this one
const text = [];
const { data } = this.testVar;
for (let item of this.testVar.data) {
Object.keys(item).forEach(key => {
text.push(key + ': ' + item[key]);
});
}
return text.join('\r\n'); // \r\n is the line break
}
最佳答案
您可以使用 json
管道将对象格式化为 json
字符串:
[(ngModel)]="mainStepText | json"
如果您想显示对象的特定属性,可以在模板中访问它:
[(ngModel)]="mainStepText.data[0].title"
这将在您的字段中显示“Test1”。
关于json - 从 json Angular 读取数据到 textarea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44393825/