代码之家  ›  专栏  ›  技术社区  ›  jamesharvey

如何使用*ngFor指令从Ionic 3(Cordova、Ionic 3、Angular 5)上的存储器中提取数据

  •  0
  • jamesharvey  · 技术社区  · 6 年前

    我正在使用爱奥尼亚的存储来保存javascript数据对象,该对象有几个属性。我正在尝试创建一个收藏夹列表,它可以从离子存储中获取数据。

    这是我的数据 提供商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);
    }
    

    这会将项目及其属性保存到Ionic storage。我可以在浏览器的inspect上看到它->应用程序页。

    我正在尝试将项目从ionic storage提取到最喜欢的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 storage中的每个项目提取到最喜爱的HTML页面?

    提前感谢,

    1 回复  |  直到 6 年前
        1
  •  1
  •   Taylor Rahul    6 年前

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

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