简体   繁体   English

解析角度4中的嵌套json(IONIC)

[英]Parse nested json in angular 4 (IONIC)

I need to parse nested JSON in my Ionic List. 我需要在我的Ionic列表中解析嵌套的JSON。 my I need to get something like this 我我需要得到这样的东西

I am using IONIC and Angular 4. 我正在使用IONIC和Angular 4。

在此处输入图片说明

My JSON format is : 我的JSON格式是:

{
    "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: 我正在使用功能获取json:

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: 在API控制器中:

 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? 如何在Angular中遍历此JSON? As the key itself is text to be printed I stuck at parsing this JSON. 由于密钥本身就是要打印的文本,因此我坚持解析此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 未捕获(承诺):TypeError:无法读取未定义的属性“结果” TypeError:无法读取未定义的属性“结果”

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. @JB Nizet@Sajeetharan我将代码更改为HttpClient,并在控制台中获取了响应json。 But when i added the code to html as mentioned by @Sajeetharan i got error : 但是当我将代码添加到@Sajeetharan提到的html中时, @Sajeetharan了错误:

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) 错误错误:未捕获(承诺):TypeError:无法读取未定义的属性“结果” TypeError:无法读取Object.eval上未定义的属性“结果”(作为updateDirectives)(IndianstudiesPage.html:24)

As @JB Nizet mentioned in the comments, use HttpClient instead of Http , here is the sample code, 正如@JB Nizet在评论中提到的,使用HttpClient代替Http ,这是示例代码,

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, 由于您具有嵌套数组,因此需要使用嵌套ngFor,因此将HTML更改为

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

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

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