1

I need to parse nested JSON in my Ionic List. my I need to get something like this

I am using IONIC and Angular 4.

enter image description here

My JSON format is :

{
    "result": {
        "engineering": [{
            "name": "Tamil Nadu",
            "colleges": {
                "list": [{
                    "id": "1",
                    "title": "wdwd"
                }, {
                    "id": "2",
                    "title": "titlealsadasbum2"
                }]
            }
        }, {
            "name": "Kerala",
            "colleges": {
                "list": [{
                    "id": "3",
                    "title": "titleqqwalbum2"
                }, {
                    "id": "4",
                    "title": "titleaasalbum2"
                }]
            }
        }],
        "medicine": [{
            "name": "Tamil Nadu",
            "colleges": {
                "list": [{
                    "id": "1",
                    "title": "med-wdwd"
                }, {
                    "id": "2",
                    "title": "med-titlealsadasbum2"
                }]
            }
        }, {
            "name": "Kerala",
            "colleges": {
                "list": [{
                    "id": "3",
                    "title": "med-titleqqwalbum2"
                }, {
                    "id": "4",
                    "title": "med-titleaasalbum2"
                }]
            }
        }]
    }
}

List :

<ion-list padding>
    <ion-list-header color="primary">TamilNadu</ion-list-header>
    <ion-item>VIT UNIVERSITY CHENNAI    </ion-item>
    <ion-item>SRM UNIVERSITYCHENNAI</ion-item>
    <ion-item>VELTECH UNIVERSITY</ion-item>
    <ion-list-header> Kerala</ion-list-header>
    <ion-item>HINDUSTAN UNIVERSITY</ion-item>
    <ion-item>SRM UNIVERSITYCHENNAI</ion-item>
    <ion-item>VELTECH UNIVERSITY</ion-item>
    <ion-list-header> Karnataka</ion-list-header>
    <ion-item>VIT UNIVERSITY CHENNAI    </ion-item>
    <ion-item>SRM UNIVERSITYCHENNAI</ion-item>
    <ion-item>VELTECH UNIVERSITY</ion-item>
    <ion-list-header>Andra Pradesh</ion-list-header>
    <ion-item>VIT UNIVERSITY CHENNAI    </ion-item>
    <ion-item>SRM UNIVERSITYCHENNAI</ion-item>
    <ion-item>VELTECH UNIVERSITY</ion-item>
</ion-list>

I am getting the json using the function:

getIndianCollegeSearchData() {
    this.showLoader();
    this.apiService.getCollegeData().then((result) => {
      console.log(result);
      this.loading.dismiss();
      this.searchResults = result
      this.items = Object.keys(this.searchResults.result);
  }, (err) => {
    this.loading.dismiss();
    console.log(err);
  });

In API controller:

 getCollegeData(){
    return new Promise((resolve, reject) => {
      let headers = new Headers();
      headers.append('Authorization', this.authService.token);
      this.http.get('http://13.126.17.194/colleges.php')
        .map(res => res.json())
        .subscribe(data => {
          resolve(data);
        }, (err) => {
          reject(err);
        });
    });

  }

How could I loop through this JSON in Angular? As the key itself is text to be printed I stuck at parsing this JSON.

I tried this method:

 <ion-list-header color="primary" *ngFor="let key of items">{{key}}</ion-list-header>

Uncaught (in promise): TypeError: Cannot read property 'result' of undefined TypeError: Cannot read property 'result' of undefined

UPDATE: I added the object as mentioned below. But how could i get values inside key engineering?

UPDATE

As mentioned by @JB Nizet and @Sajeetharan i changed the code to HttpClient i get the response json in console. But when i added the code to html as mentioned by @Sajeetharan i got error :

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'result' of undefined TypeError: Cannot read property 'result' of undefined at Object.eval [as updateDirectives] (IndianstudiesPage.html:24)

7
  • 3
    Object.keys(this.searchResults.result). developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. While you're at it, learn and use HttpClient. The Http service is deprecated. And learn observables. Wrapping observables into promises as you're doing is clumsy. At least use the toPromise() operator. Commented Jan 1, 2018 at 10:25
  • @JBNizet . where i need to add this code? I am using ng repeat to populate list. Commented Jan 1, 2018 at 10:30
  • Wherever you want to access the keys of your result object. Your view should work on a model that is suited for what it has to do. So make your service aor component transform the data you get from the server into a format that is usable by the view. Commented Jan 1, 2018 at 10:32
  • I thought ng-repeat is for angularJs not Angular. Can someone explain ? Commented Jan 1, 2018 at 10:33
  • 1
    @Melchia it is. Not sure why the OP is trying to use ng-repeat instead of *ngFor. But that's another matter. Commented Jan 1, 2018 at 10:36

2 Answers 2

2

Finally founded a solution:

Use safe navigator operator:

 <ion-list>
        <ion-list-header *ngFor="let details of searchResults?.result?.engineering">
          {{details.name}}
          <ion-item no-lines *ngFor="let detail of details?.colleges" (click)="itemSelected(detail.id)" >{{detail.title}}</ion-item>
        </ion-list-header>
      </ion-list>
Sign up to request clarification or add additional context in comments.

Comments

0

As @JB Nizet mentioned in the comments, use HttpClient instead of Http , here is the sample code,

Inside your service,

import {HttpClient, HttpHeaders} from '@angular/common/http';

private static defaultHeaders(): HttpHeaders {
    return new HttpHeaders({'Content-Type' : 'application/json'});
}

constructor(
    private httpClient: HttpClient
) {}

getCollegeData(): Observable<any> {
    const headers: HttpHeaders = new Headers();
    return this.httpClient.get<any>('http://13.126.17.194/colleges.php', {headers: headers.append('Authorization', this.authService.token)});
}

and then inside your component

ngOnInit() {
   this.apiService.getCollegeData().subscribe((colleges) =>  this.searchResults = colleges);
}

You need to use nested ngFor since you have nested arrays, so change your HTML as,

<ion-list-header color="primary" *ngFor="let details of searchResults.result.engineering">
 <ng-container *ngFor="let detail of details.colleges.list">
   {{detail.title}}
 </ng-container>
</ion-list-header>

you might need to change a little bit if you find some issues.

5 Comments

const headers: HttpHeaders = new Headers(); here is it suppose to be const headers: HttpHeaders = new HttpHeaders(); right?
also here what is Product[] ? Its showing error there?
I remove Product[], and when run i got ERROR TypeError: Cannot read property 'result' of undefined
it should be any , not product
Yes tried that still its showing error.. I get response in console.. but when i added ngFor, Its showing above mentioned error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.