0
我試圖在存儲中保存一個名稱數組,並在用戶單擊按鈕時檢索它們。 查看有一個文本框和一個按鈕,用戶可以使用該按鈕輸入任意數量的名稱,並在組件中獲取它們並將它們保存到存儲中。 要檢索存儲的名稱,我提供了一個按鈕和用戶點擊它,我想要顯示所有保存的名稱(使用for循環或迭代它)ionic2-在存儲器中保存數組
當我嘗試保存多個名稱時,出現錯誤:
Uncaught (in promise): TypeError: _this.names.push is not a function
只有當我嘗試保存多個名稱時纔會出現此錯誤。
這裏的觀點:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
names =[];
constructor(public navCtrl: NavController, public storage: Storage) {
}
fetchAllNames(){
this.storage.ready().then(
() => {
// Or to get a key/value pair
this.storage.get('name').then((val) => {
console.log('Your age is', val);
})
});
}
storeThisName(name){
console.log(name);
this.storage.ready().then(
() => {
this.storage.get('name').then((val) => {
console.log('Your age is', val);
this.names= val;
this.names.push(name);
// set a key/value
this.storage.set('name', this.names);
})
});
}
}
可能是什麼可能的錯誤:下面
<ion-navbar *navbar>
<ion-title>New category</ion-title>
</ion-navbar>
<ion-content class="addtrans">
<button ion-button (click)="fetchAllNames()">Show Names!</button>
<input type="text" id="name" #named>
<button ion-button (click)="storeThisName(named.value)">Store This!</button>
</ion-content>
對這一觀點的.ts文件中給出? 注意:app.module.ts文件配置正確。
什麼是從存儲返回的'val' – Aravind
您有'this.names = val; this.names.push(name);'val和name的數據類型是什麼 –
可能是'this.names = val;'賦值時間,'val'可能是未定義的。你可以考慮讓它成爲'this.names = val || [];' –