我通过Ionic Storage存储JSON数组,如下所示:
this.storage.set('data', this.data).then().catch(err => {
this.data.splice(this.data.indexOf(Data), 1);
});
并在函数中获取它:
fetchData(){
this.storage.get('data').then(
(data: {value: string, usage: string, date: string, addedDate: string}[]) => {
this.data = data != null ? data : [];
console.log('DATA FETCHED: ' + data);
return data;
}
).catch(err => {
console.log(err);
});
}
我在数组中存储了4个对象,但是console.log只是给了我这个:
DATA FETCHED: [object Object],[object Object],[object Object],[object Object]
如何才能正确显示数组?我已经尝试过.toString()和.slice()
home.html中的相关部分:
<ion-item *ngFor="let item of items">
<h2>{{ item.usage }}</h2>
<p>{{ item.date | date:'dd MMM yyyy' }}</p>
<h1 item-end ngClass="{{ item.value.charAt(0) === '-' ? 'expense' : 'income' }}">{{ item.value }} €</h1>
<!--<h1 item-end class="income">+ 450,00 €</h1>!-->
</ion-item>
home.ts:
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
items: any = this.moneyService.fetchData();
incomeval: any = IncomevalPage;
expenseval: any = ExpensevalPage;
constructor(public navCtrl: NavController, private moneyService: MoneyService) {}
ionViewWillEnter(){
this.items = this.moneyService.fetchData();
}
}
答案 0 :(得分:1)
我认为,除了Marco在答案中所说的,问题在于你没有从fetchData()
返回任何内容。 return语句在promise中。 Promise可能需要一段时间才能习惯,但是如果你返回结果,它将是一个带有新值的新承诺。用一个例子可能更容易理解:
var promise = Promise.resolve("first").then(val => "second");
promise.then(val => console.log("val is", val));
// Prints: "val is second"
您正在设置this.data
的{{1}},但未在MoneyService
组件中的任何位置访问。
如果您将HomePage
更改为此内容,该怎么办:
fetchData
它现在将返回一个承诺,您必须在fetchData(){
return this.storage.get('data').then((data: {value: string, usage: string, date: string, addedDate: string}[]) => {
return data != null ? data : [];
});
}
中正确处理,可能是这样的(未经测试):
HomePage
只要数据可用,它就会更新@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
items: any;
incomeval: any = IncomevalPage;
expenseval: any = ExpensevalPage;
constructor(public navCtrl: NavController, private moneyService: MoneyService) {
moneyService.fetchData().then(result => this.items = result);
}
}
。
答案 1 :(得分:0)
您需要对home.ts
进行一些更正:
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
items: any;
moneyService: any;
incomeval: any = IncomevalPage;
expenseval: any = ExpensevalPage;
constructor(public navCtrl: NavController, data: MoneyService) {
this.items = null;
this.moneyService = data;
}
ionViewWillEnter(){
this.items = this.moneyService.fetchData();
}
}