我的JSON是什么样的:
{
"reportSections": [
{
"name": "...",
"display": true,
"nav": false,
"reportGroups": {
"reports": [
{
"name": "...",
"url": "reportLibrary.tableau",
"nav": true,
"params": {
"reportName": "clientRelationshipReport",
"reportTitle": "Client Relationship Report",
"reportUrl": "...",
"reportHeight": "4030px"
},
"filters": "clientName,brokerName,entity,budgetClass,practice,office"
}
]
}
}
]
}
组件中的我的HTML文件模板
<li *ngFor = "let sectionName of reportNavJSONMain.reportSections">
<span> {{ sectionName.name }} </span>
<ul>
<li *ngFor="let report of sectionName.reportGroups.reports">
<a *ngIf="report.nav"> {{report.name}} </a>
</li>
</ul>
</li>
我的component.ts方法是什么样的:
//<irrelevant code>
....
getReports(): any {
new Promise((resolve,reject)=>{
resolve(
this.reportNavService.getJSONReportMain()
)
}).then((data)=>{
// console.dir(JSON.parse(JSON.stringify(data)));
this.reportNavJSONMain = JSON.stringify(data);
console.dir(this.reportNavJSONMain )
})
}
...
//<irrelevant code>
我的服务代码:
//....
public getJSONReportMain(): Promise<any> {
return this.http.get('...')
.toPromise()
.then((response: Response)=>{
//console.log(JSON.stringify(response.json()))
this.reportNavJSON = JSON.stringify(response.json());
return this.reportNavJSON;
}).catch((error: Response)=>{
return Observable.throw('Error');
});
}
// ....
在component.ts文件中,我已将this.reportNavJSONMain
初始化为对象(我还将其初始化为对象数组)但是当我在console.log()或console.dir()时,它总是将其显示为&#34;对象&#34;。我尝试了JSON.parse(),JSON.stringify()和两者,但都没有奏效。
我的目标是从reportSections
访问this.reportNavJSONMain
,但当我this.reportNavJSONMain.reportSections
时,reportSections不是this.reportNavJSONMain的一部分。但是,当我console.dir(this.reportNavJSONMain)
或console.log(this.reportNavJSONMain)
时,会显示以下内容:
{"reportSections":[
{"name":"...","display":true,"nav":true,"reportGroups":
{"reports":
[{"name":"Client Relationship Report","url": .....}
答案 0 :(得分:1)
您无法导航/迭代字符串,但您可以使用对象!
(我认为this.reportNavJSONMain
被宣布为var
或Object
)
如果数据类型为Object
).then((data)=>{
this.reportNavJSONMain = data;
})
如果数据类型为String
).then((data)=>{
this.reportNavJSONMain = JSON.parse(data);
})
<小时/> 一个如何在Javascript中实现它的示例,
var object = {
"reportSections": [
{
"name": "...",
"display": true,
"nav": false,
"reportGroups": {
"reports": [
{
"name": "...",
"url": "reportLibrary.tableau",
"nav": true,
"params": {
"reportName": "clientRelationshipReport",
"reportTitle": "Client Relationship Report",
"reportUrl": "...",
"reportHeight": "4030px"
},
"filters": "clientName,brokerName,entity,budgetClass,practice,office"
}
]
}
}
]
}
var p = new Promise((resolve, reject) => {
resolve(object);
});
p.then((data) => {
data.reportSections.forEach((section) => {
console.log(section.reportGroups);
})
});
&#13;