首页 文章

如何从Ionic 3上的存储使用* ngFor指令获取数据(Cordova,Ionic 3,Angular 5)

提问于
浏览
-1

我正在使用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指令从提供程序中获取项目 .

Main HTML:

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

Main TS file:

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

这会将项目及其属性保存到Ionic存储 . 我可以在浏览器的inspect - > application页面上看到它出现 .

我正在尝试将离子存储中的项目提取到喜欢的HTML页面 .

Favorite HTML page:

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

Favorite TS file

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

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

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

提前致谢,

1 回答

  • 2

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

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

相关问题