its.david
its.david

Reputation: 2235

Accessing items inside a JSON [Using Typescript/Angular2]

What my JSON looks like:

{
  "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

<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:

//<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". I tried JSON.parse(), JSON.stringify(), and both but none of it worked.

My goal here is to access reportSections from this.reportNavJSONMain but when I do this.reportNavJSONMain.reportSections, reportSections is not part of this.reportNavJSONMain. However when I console.dir(this.reportNavJSONMain) or console.log(this.reportNavJSONMain), it displays this:

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

Upvotes: 3

Views: 167

Answers (2)

Zze
Zze

Reputation: 18805

You can't navigate / iterate a string, but you can an object!

(I assume this.reportNavJSONMain was declared either as a var or Object)

If data is of type Object

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

If data is of type String

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


An example of how to implement this in 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);
  })
});

Upvotes: 1

David Sherman
David Sherman

Reputation: 440

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. This way you emmediately have the result as json.

Upvotes: 0

Related Questions