【问题标题】:How to read attribute "name" of my json array in Ionic如何在 Ionic 中读取我的 json 数组的属性“名称”
【发布时间】:2019-05-06 23:17:35
【问题描述】:

json array localstorage format

您好,我正在开发一个 ionic 应用程序。我是 Ionic 和 Typescript 的新手。

正如您在下图中看到的,我正在从 API 解析我的 json 数组中的数据。

在 ts 文件上我正在编写这段代码

` 公共类别详细信息:任何;

const datacat = JSON.parse(localStorage.getItem('categoryData')); this.categoryDe​​tails = datacat.categoryData;`

当我写这个时在我的html文件中

<h1 class="business-top">Business of the category {{categoryDetails.name}}</h1>

我收到错误消息“TypeError: Cannot read property 'name' of undefined”

我知道我没有正确读取属性“名称”。我该怎么做?

此外,如何显示与类别的特定 term_id 关联的企业?

【问题讨论】:

    标签: arrays json typescript ionic3


    【解决方案1】:

    在这个例子中你需要这样做

    <h1 class="business-top">Business of the category {{categoryDetails?.name}}</h1>
    
    public categoryDetails: any;
    
    this.categoryDetails = localStorage.getItem('categoryData');
    

    或者您可以使用离子存储。如果你使用离子会更好。

    https://ionicframework.com/docs/storage/

    import { Storage } from '@ionic/storage';
    
    export class MyApp {
    public categoryDetails: any;
      constructor(private storage: Storage) { }
    
      ...
    
      // set a key/value
      storage.set('categoryData', 'Max');
    
      // Or to get a key/value pair
      storage.get('categoryData').then((val) => {
        this.categoryDetails = val;
      });
    }
    

    【讨论】:

    • 您的第一个建议无效。将出现一个空白字段,其中应显示类别名称。关于第二个,我的整个应用程序都基于 localStorage。我从 Mysql DB 中获取我的数据作为 Json 数组。正如您在所附照片中看到的,使用const datacat = JSON.parse(localStorage.getItem('categoryData')); this.categoryDetails = datacat.categoryData; 可以很好地读取 userData。但是数组中的所有其他 Json 都不能用相同的方法读取?如何从 businessData 和 CategoryData 读取属性?
    【解决方案2】:

    我终于弄明白了。

    @Kilomat 感谢您对使用离子存储的帮助和建议。这让我免于未来的问题。

    关于我所做的 json 文件。

    在我的 HTML 代码中 <ion-grid no-margin> <h1 class="business-top">Επιχειρήσεις της κατηγορίας {{businessData.name}} {{businessData.term_id}}</h1> <ion-list> <ion-item class="col col-50" *ngFor="let c of BusinessCategoryDetails" text-wrap (click)="product(c)"> <div *ngIf="c.term_id == businessData.term_id"> <h2>{{c.post_title}} {{c.term_id}}</h2> <img width="80" height="80" src="{{c.guid}}"> </div> </ion-item> </ion-list> </ion-grid>

    在我的 TS 代码中 `var businessCategory: categories = navParams.get("businessCategory"); console.log(businessCategory); /导出所选类别/

    var newData = JSON.stringify(businessCategory);
    this.businessData = JSON.parse(newData);`
    

    它从我以前的类别页面中获取属性和值。 TS代码

    `类别:[categoryDe​​tails] = null;

    gotobusiness(类别:类别){ this.navCtrl.push(BusinessPage, { businessCategory: category}); }`

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-08
      • 2021-12-07
      • 1970-01-01
      • 2021-12-18
      • 2022-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多