Arrays 如何从Ionic中保留数组中的数据-this.array.push不是一个函数

Arrays 如何从Ionic中保留数组中的数据-this.array.push不是一个函数,arrays,angular,typescript,ionic-framework,storage,Arrays,Angular,Typescript,Ionic Framework,Storage,数组storedArr=[]用于使用存储来存储数据,但是,我收到了。当我尝试使用存储get方法填充它时,push不是一个函数: storedArr = this.storage.get('stored') ? this.storage.get('stored').then((e) => {e}) : []; 我的代码的主要部分是: import { Storage } from '@ionic/storage'; export class MyPage { constructo

数组
storedArr=[]
用于使用存储来存储数据,但是,我收到了
。当我尝试使用存储get方法填充它时,push不是一个函数

storedArr = this.storage.get('stored') ? this.storage.get('stored').then((e) => {e}) : [];
我的代码的主要部分是:

import { Storage } from '@ionic/storage';

export class MyPage {
    constructor(
        private storage: Storage) {
    }

    // storedArr = []; This works but resets the array

    storedArr = this.storage.get('stored') ? this.storage.get('stored').then((e) => {e}) : [];

    saveToStorage() {
        this.storedArr.push({ // .push is not a function
          title: 'blabla',
          body: 'more blabla'
        });

        this.storage.set('stored', this.storedArr);
    }
}

我应该如何编写这部分代码

如果存储的不是简单的原语值,则可能需要对存储getter结果执行
JSON.parse()
。像下面这样。我调整了使用wait(代替您的
then
s),我认为这更清楚

var storageResult = await this.storage.get('stored');
storedArr = (storageResult) ? JSON.parse(storageResult) : [];
此外,在存储数组时,您可能希望对其执行
JSON.stringify

this.storage.set('stored', JSON.stringify(this.storedArr));

Ionic
this.storage.get
实际上除了必须“订阅”的承诺之外,不返回任何值

所以
storedArr=this.storage.get('storage')?get('storage')。然后((e)=>{e}):[]实际上在
storedArr
中存储一个承诺,失败时它仍然返回一个承诺。因此出现了错误-因为
Promise.prototype
不包含
push
方法。因此,三元运算符将计算为
true
,因此
[]
分配给
storedArr

为了获得Ionic
this.storage.get('stored')
的值,您必须“订阅”返回的承诺,然后将
数据
参数分配给
storedArr
。就像这样

export class MyPage {
  storedArr = [];

  constructor(private storage: Storage) {
      this.storage.get('stored')
          .then(data => {
            this.storedArr = data;
          });
  }

  saveToStorage() {
      this.storedArr.push({ // .push is not a function
        title: 'blabla',
        body: 'more blabla'
      });

      this.storage.set('stored', this.storedArr);
  }
}

你的回答让我注意到我可以这样写我的初始代码:storedArr=this.storage.get('storage')?this.storage.get('stored')。然后(e=>this.storedArr=e):[];是的,我会工作的。但这很奇怪,而且它变得更难阅读和理解。而是将“订阅”移动到
ngInit()
(Angular的建议)或构造函数(如我在答案中所示)。哦,我已经稍微澄清了答案。请再读一遍(但解决方案保持不变)。