Ionic 4视图的列表不会立即更新

时间:2019-03-10 14:47:05

标签: typescript ionic-framework ionic4

我已经在Ionic 4中编写了一个简单的购物清单应用程序。本质上,该应用程序具有Ionic's Storage的CRUD功能。

用户通过键入item并按“添加”按钮,将新的items添加到name。我可以成功地向存储中添加新的item,但是局部变量不会立即更新,而是会滞后一个item

重现该错误:

  1. 输入一些内容,例如“面包”,然后按“添加”按钮
  2. 尽管存储现在包含“ bread”项,但仍然可以观察视图中没有任何内容:[{name: "bread", timestamp: 1552228855301}]
  3. 例如,重复步骤1。 “黄油”,然后观察视图列表如何显示面包。该视图的列表始终落后一个item
  4. 您需要向存储中添加第三项,以使第二项在视图中可见。

不幸的是,由于错误,我无法提供Stackblitz,但是这里有一些代码:

home.page.html:

<ion-header>
  <ion-toolbar>
    <ion-title>
      Shopping list
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>
  <ion-list>
    <ion-item>
      <ion-input placeholder="New item's name" [(ngModel)]="item.name"></ion-input>
    </ion-item>
  </ion-list>

  <ion-button expand="block" (click)="addToShoppingList(item)">Add</ion-button>

  <ion-list>
    <ion-list-header>
      <ion-label>Shopping list 1</ion-label>
    </ion-list-header>
    <ion-item *ngFor="let item of items">
      {{ item.name }}
    </ion-item>
  </ion-list>

  <ion-fab vertical="bottom" horizontal="end" slot="fixed">
    <ion-fab-button (click)="navigate()">
      <ion-icon name="add"></ion-icon>
    </ion-fab-button>
  </ion-fab>
</ion-content>

item.interface.ts:

export interface item {
    timestamp: number,
    name: string
}

home.page.ts:

import { Component } from '@angular/core';
import { ShoppinglistService } from '../shoppinglist.service';
import { item } from '../item';
import { Router } from '@angular/router';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  items: item[] = [];
  item = {} as item;

  constructor(private service: ShoppinglistService, private router: Router) { }

  ngOnInit() {
    this.service.getAll().then((val) => {
      this.items = val;
    })
  }

  addToShoppingList = (item) => {
    this.item.timestamp = new Date().getTime();
    this.service.addOne(item);
    this.ngOnInit();
  }

  navigate() {
    this.router.navigate(['/newitem'])
  }

}

shoppinglist.service.ts:

import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import { item } from '../app/item';

@Injectable({
  providedIn: 'root'
})
export class ShoppinglistService {

  constructor(private storage: Storage) { }

  getAll = (): Promise<item[]> => {
    return new Promise((resolve, reject) => {
      this.storage.get('shoppinglist').then((val: item[]) => {
        resolve(val);
      }, (error) => {
        reject(error);
      });
    })
  }

  addOne = (newitem: item): void => {
    this.storage.get('shoppinglist').then((val) => {
      console.log(val)
      let items: item[] = val;
      if (items == null) {
        items = [];
      }
      items.push(newitem);
      this.storage.set('shoppinglist', items);
    })
  }

}

0 个答案:

没有答案