ionic2-在存储中保存一个数组

时间:2017-05-01 12:46:09

标签: angular ionic-framework ionic2

我正在尝试在存储中保存一组名称,并在用户单击按钮时检索它们。 View有一个文本框和一个按钮,用户可以使用该按钮输入任意数量的名称,在组件中,我获取它们并想将它们保存到存储中。 要检索存储的名称,我提供了一个按钮,用户点击它,我想显示所有保存的名称(使用for循环或其他东西迭代它)

当我尝试保存多个名称时,出现错误:

Uncaught (in promise): TypeError: _this.names.push is not a function

只有在我尝试保存多个名称时才会出现此错误。

以下是观点:

<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文件如下:

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

}

可能出现的错误是什么? 注意:app.module.ts文件配置正确。

1 个答案:

答案 0 :(得分:2)

我怀疑this.names= val;代码行存在问题。如果收集没有通过API返回,那么它将是未定义的。因此,确切的下一步操作将失败this.names.push(name);

对于这种情况,您应该将代码更改为下面的代码,如果没有从服务器返回集合,则会分配[]

this.names= val || [];
this.names.push(name);