简体   繁体   English

访问JSON中的项目[使用Typescript / Angular2]

[英]Accessing items inside a JSON [Using Typescript/Angular2]

What my JSON looks like: 我的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"
          }
        ]
      }
    }
  ]
}

My HTML File template in the component 我在组件中的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>

What my component.ts method looks like: 我的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>

My service 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');
      });
  }
  // ....

In component.ts file, I have initialized this.reportNavJSONMain as an object (I have also initialized it as an array of objects) but when I console.log() or console.dir() it, it always displays it as an "Object". 在component.ts文件中,我已将this.reportNavJSONMain初始化为一个对象(我还将其初始化为一个对象数组)但是当我在console.log()或console.dir()时,它总是将其显示为“宾语”。 I tried JSON.parse(), JSON.stringify(), and both but none of it worked. 我尝试了JSON.parse(),JSON.stringify()和两者,但都没有奏效。

My goal here is to access reportSections from this.reportNavJSONMain but when I do this.reportNavJSONMain.reportSections , reportSections is not part of this.reportNavJSONMain. 我的目标是从this.reportNavJSONMain访问reportSections但是当我执行this.reportNavJSONMain.reportSections ,reportSections不是this.reportNavJSONMain的一部分。 However when I console.dir(this.reportNavJSONMain) or console.log(this.reportNavJSONMain) , it displays this: 但是当我在console.dir(this.reportNavJSONMain)console.log(this.reportNavJSONMain) ,它会显示:

{"reportSections":[
     {"name":"...","display":true,"nav":true,"reportGroups":
          {"reports":
              [{"name":"Client Relationship Report","url": .....}

You can't navigate / iterate a string, but you can an object! 你不能导航/迭代一个字符串,但你可以一个对象!

(I assume this.reportNavJSONMain was declared either as a var or Object ) (我假设this.reportNavJSONMain被声明为varObject

If data is of type Object 如果数据是Object类型

).then((data)=>{
    this.reportNavJSONMain = data;
})

If data is of type String 如果数据类型为String

).then((data)=>{
    this.reportNavJSONMain = JSON.parse(data);
})


An example of how to implement this in Javascript, 一个如何在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); }) }); 

You're turning your JSON result into a string with JSON.stringify(), on your http result you want to call result.json() in your service. 您将JSON结果转换为带有JSON.stringify()的字符串,在您的http结果中,您要在服务中调用result.json()。 This way you emmediately have the result as json. 这样你就可以立即得到json的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM