【问题标题】:How to fetch data using *ngFor directive from storage on Ionic 3 (Cordova, Ionic 3, Angular 5)如何使用 *ngFor 指令从 Ionic 3(Cordova、Ionic 3、Angular 5)上的存储中获取数据
【发布时间】:2018-10-08 21:14:30
【问题描述】:

我正在使用 Ionic 的存储来保存具有多个属性的 javascript 数据对象。我正在尝试创建一个可以从离子存储中获取数据的收藏列表。

这是我的数据 provider TS 文件。

  private items: any[] = [

    {
   "name": "item 01",
   "description": "this is item 01",
   "id": "1"
   },
    {
   "name": "item 02",
   "description": "this is item 02",
   "id": "2"
   },
    {
   "name": "item 03",
   "description": "this is item 03",
   "id": "3"
   },
   {
"name": "item 04",
 "description":"this is item 04",
 "id":"4"
 }
]

我正在使用一个按钮将项目保存在我的 html 文件中。 主 HTML 文件使用 *ngFor let of 指令从提供程序获取项目。

主 HTML:

<div *ngFor="let item of items"> 
  <h2>{{item.name}}</h2>  
  <p>{{item.description}}</p>
  <button (click)="saveToFav(item)">Save to favorites</button>
</div>

主 TS 文件:

savToFav(item) {
this.storage.set(this.item.id, this.item);
}

这会将项目及其属性保存到离子存储中。我可以看到它出现在我的浏览器的检查 -> 应用程序页面上。

我正在尝试将项目从离子存储获取到最喜欢的 HTML 页面。

最喜欢的 HTML 页面:

  <div *ngFor="let item of items"> 
      <h2>{{item.name}}</h2>  
      <p>{{item.description}}</p>
      <button (click)="remove(item)">Remove from favorites</button>
    </div>

收藏的 TS 文件

    this.platform.ready().then(() => {
    this.storage.get(this.item);
});

但这真的不会在最喜欢的 html 页面上加载任何内容..

我应该怎么做才能将存储在 Ionic 存储中的每个项目获取到最喜欢的 HTML 页面?

提前致谢,

【问题讨论】:

标签: angular cordova ionic-framework ionic2 ionic3


【解决方案1】:

您以错误的方式使用存储获取和设置功能,所有收藏的项目必须存储在一个键中,以便以后需要时您可以拥有所有收藏列表。应该像下面这样的

savToFav(item) {
  this.storage.get('favoritesList')
  .then((fav)=>{
    if(fav == null){
       fav = [];
    }
    //This will fetch the old items and push the new item in array
    fav.push(item); return fav;
  })
  .then((fav)=>{
    //this will store the new update favorite list array in storage.
    this.storage.set('favoritesList',fav);
  })
}

//Favorite ts file you can use it like below 
this.storage.get('favoritesList').then((fav)=>{
 //you can asssing it any variable and use in your *ngFor loop
  this.myFavList = fav;
})

【讨论】:

  • 感谢您的回复!您如何将其分配给 this.storage.get('favoritesList').then((fav)=>{ }) 中的变量?我现在正在尝试。
  • 和“push”会引发错误消息。它说'无法读取 null TypeScript 错误的属性'push'
  • 您可以为这种情况添加支票
  • @jamesharvey 我已编辑答案以添加对 null 的检查
  • 谢谢!我通过使用接口和数组解决了这个问题!
猜你喜欢
  • 2018-10-10
  • 2018-10-02
  • 2020-08-29
  • 1970-01-01
  • 1970-01-01
  • 2018-02-22
  • 1970-01-01
  • 2021-12-19
  • 2018-06-21
相关资源
最近更新 更多