【问题标题】:Parse nested json in angular 4 (IONIC)以角度 4 (IONIC) 解析嵌套的 json
【发布时间】:2018-06-11 10:38:12
【问题描述】:

我需要在我的 Ionic List 中解析嵌套的 JSON。 我需要这样的东西

我正在使用 IONIC 和 Angular 4。

我的 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"
                }]
            }
        }]
    }
}

列表:

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

我正在使用函数获取 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);
  });

在 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);
        });
    });

  }

如何在 Angular 中循环遍历这个 JSON?由于密钥本身是要打印的文本,所以我一直在解析这个 JSON。

我试过这个方法:

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

未捕获(承诺中):TypeError:无法读取属性“结果” 未定义类型错误:无法读取未定义的属性“结果”

更新: 我添加了如下所述的对象。但是我怎样才能在关键工程中获得价值呢?

更新

正如 @JB Nizet@Sajeetharan 所述,我将代码更改为 HttpClient,我在控制台中获得了响应 json。但是,当我将代码添加到 @Sajeetharan 提到的 html 时,我得到了错误:

ERROR 错误:未捕获(承诺中):TypeError:无法读取属性 未定义类型错误的“结果”:无法读取属性“结果” 不明确的 在 Object.eval [as updateDirectives] (IndianstudiesPage.html:24)

【问题讨论】:

  • Object.keys(this.searchResults.result)developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。在您使用它的同时,学习和使用 HttpClient。 Http 服务已弃用。并学习 observables。将 observables 包装成 Promise 是很笨拙的。至少使用 toPromise() 运算符。
  • @JBNizet。我需要在哪里添加此代码?我正在使用 ng repeat 来填充列表。
  • 无论您想在哪里访问结果对象的键。您的视图应该适用于适合它必须做的事情的模型。因此,让您的服务或组件将您从服务器获取的数据转换为视图可用的格式。
  • 我认为 ng-repeat 适用于 angularJs 而不是 Angular。谁能解释一下?
  • @Melchia 是。不知道为什么 OP 尝试使用 ng-repeat 而不是 *ngFor。但那是另一回事了。

标签: angular ionic-framework


【解决方案1】:

正如cmets中提到的@JB Nizet,使用HttpClient代替Http,这里是示例代码,

在您的服务中,

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)});
}

然后在你的组件内部

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

你需要使用嵌套的 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>

如果您发现一些问题,您可能需要稍作更改。

【讨论】:

  • const headers: HttpHeaders = new Headers(); 这里应该是const headers: HttpHeaders = new HttpHeaders(); 对吧?
  • 还有Product[] 是什么?它在那里显示错误?
  • 我删除了Product[],运行时我得到了ERROR TypeError: Cannot read property 'result' of undefined
  • 应该是 any,而不是 product
  • 是的,它仍然显示错误。我在控制台中得到响应。但是当我添加 ngFor 时,它显示上述错误。
【解决方案2】:

终于找到了解决方案:

使用安全导航操作符:

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

【讨论】:

    猜你喜欢
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 2018-08-06
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多