首页 > 解决方案 > 如何在 Ionic 中读取我的 json 数组的属性“名称”

问题描述

json数组本地存储格式

你好,我正在开发一个离子应用程序。我是 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:无法读取未定义的属性‘名称’”

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

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

标签: arraysjsontypescriptionic3

解决方案


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

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

推荐阅读