0

我通过 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 }} €&lt;/h1>
    <!--<h1 item-end class="income">+ 450,00 €&lt;/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();
  }
}
4

2 回答 2

1

我认为,除了 Marco 在他的回答中所说的之外,问题在于您没有从fetchData(). return 语句在 Promise 中。Promise 可能需要一段时间才能习惯,但如果你返回结果,它将是一个具有新值的新 Promise。举个例子可能更容易理解:

var promise = Promise.resolve("first").then(val => "second");
promise.then(val => console.log("val is", val));
// Prints: "val is second"

您正在设置this.dataMoneyService但在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);
    }
}

this.items一旦数据可用,它将立即更新。

于 2017-11-11T18:54:50.550 回答
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();
  }
}
于 2017-11-11T18:27:30.013 回答