简体   繁体   中英

Parse nested json in angular 4 (IONIC)

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.

在此处输入图片说明

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)

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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