我已经在Ionic 4中编写了一个简单的购物清单应用程序。本质上,该应用程序具有Ionic's Storage的CRUD功能。
用户通过键入item
并按“添加”按钮,将新的items
添加到name
。我可以成功地向存储中添加新的item
,但是局部变量不会立即更新,而是会滞后一个item
。
重现该错误:
[{name: "bread", timestamp: 1552228855301}]
item
。不幸的是,由于错误,我无法提供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);
})
}
}