首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在没有ngOnInit()的情况下以角显示数据?

如何在没有ngOnInit()的情况下以角显示数据?
EN

Stack Overflow用户
提问于 2019-01-31 06:50:55
回答 2查看 352关注 0票数 1

我在Ionic 4中有一个香烟计数器应用。这里是Stackblitz:https://stackblitz.com/edit/ionic-8xrdgo。当用户按下计数器段中的Add One按钮时,我需要在历史段中显示最新的消费数据。出于某种原因,需要重新加载应用程序才能在历史段中显示最新的数据。

为了重现这个问题:

  1. 在存储中不使用consumption启动应用程序
  2. 单击Add One按钮。成功地将新的消耗添加到存储中。
  3. 再次单击Add One按钮。现在应该更新现有的消费,但由于某种原因,它没有更新。此外,历史段不显示数据。
  4. 重新加载应用程序。
  5. 单击Add One按钮。现在,现有的消费被成功地更新到存储,并且消费被显示在历史段中。

这里的问题是,重新加载应用程序是必要的,以更新现有消费到存储和显示它。

这里的完整代码:

home.page.html:

代码语言:javascript
复制
<ion-header>
  <ion-toolbar>
    <ion-segment [(ngModel)]="segment" color="dark">
      <ion-segment-button value="info">
        Info
      </ion-segment-button>
      <ion-segment-button value="counter">
        Counter
      </ion-segment-button>
      <ion-segment-button value="history">
        History
      </ion-segment-button>
    </ion-segment>
  </ion-toolbar>
</ion-header>

<ion-content padding>

  <div *ngIf="segment == 'info'">
    <h1 class="center">Cigarette pack info</h1>
    <ion-item>
      <ion-input placeholder="Price" type="number" [(ngModel)]="pack.price"></ion-input>
    </ion-item>
    <ion-item>
      <ion-input placeholder="Cigarette count" type="number" [(ngModel)]="pack.cigarettecount"></ion-input>
    </ion-item>
    <br>
    <ion-button expand="block" color="dark" (click)="savePack()">Save</ion-button>
  </div>

  <div *ngIf="segment == 'counter'">
    <h1 class="center">Consumption today</h1>
    <p class="center">{{ today.date }}</p>
    <p class="center">{{ today.consumption }}</p>
    <p class="center">{{ today.last_smoked }}</p>
    <ion-button expand="block" color="dark" (click)="addOne()">Add one</ion-button>
  </div>

  <div *ngIf="segment == 'history'">
    <h1 class="center">Recent consumption</h1>
    <ion-grid>
      <ion-row>
        <ion-col><b>Date</b></ion-col>
        <ion-col><b>Consumption</b></ion-col>
      </ion-row>
      <ion-row *ngFor="let history of histories">
        <ion-col>{{ history.date }}</ion-col>
        <ion-col>{{ history.consumption }}</ion-col>
      </ion-row>
      <ion-row>
        <ion-col>-{{ money_consumption_tostring  }} €</ion-col>
      </ion-row>
    </ion-grid>
  </div>

</ion-content>

接口:

代码语言:javascript
复制
export interface pack {
    price: number,
    cigarettecount: number
}

export interface consumption {
    date: string,
    consumption: number,
    last_smoked: string
}

home.page.ts:

代码语言:javascript
复制
import { Component } from '@angular/core';
import { pack } from '../pack.interface';
import { consumption } from '../consumption.interface';
import { ConsumptionService } from '../consumption.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor(private service: ConsumptionService) { }

  segment: string = "info";
  pack: pack[] = [];
  today = {} as consumption;
  histories: consumption[] = [];
  price: number = 0;
  money_consumption: number = 0;
  money_consumption_tostring: string = "0";

  ngOnInit() {

    this.service.getConsumptions().then((data: consumption[]) => {
      if (data == null) {
        this.today.consumption = 0;
        this.today.date = new Date().toLocaleDateString();
        this.today.last_smoked = new Date().toLocaleTimeString();
      } else {
        for (let consumption of data) {
          if (consumption.date == new Date().toLocaleDateString()) {
            this.today = consumption;
          }
        }
      }

      this.service.getConsumptions().then((data: consumption[]) => {
        this.histories = data;
      })
    })

    this.service.getPack().then((data) => {
      if (data != null) {
        this.segment = "counter";
      }
    })

  }

  addOne = () => {
    this.today.date = new Date().toLocaleDateString();
    this.today.consumption += 1;
    this.today.last_smoked = new Date().toLocaleTimeString();

    this.service.getConsumptions().then((data: consumption[]) => {
      let consumptions = data;
      // at least one consumption found
      if (consumptions != null) {
        let current_exists = false;
        for (let consumption of consumptions) {
          // use current date
          if (consumption.date == this.today.date) {
            current_exists = true;
            consumption.date = this.today.date;
            consumption.consumption = this.today.consumption;
            consumption.last_smoked = this.today.last_smoked;

            // add current consumption to history
            for (let history of this.histories) {
              if (history.date == this.today.date) {
                history.date = this.today.date;
                history.consumption = this.today.consumption;
                history.last_smoked = this.today.last_smoked;
              }
            }

          }
        }
        // new date
        if (current_exists == false) {
          consumptions.push(this.today);
          this.histories.push(this.today);
        }
        this.service.saveConsumptions(consumptions);
      } else {
        // no consumptions found
        this.service.addConsumptions(this.today);
        this.histories = data;
      }
    })
  }

  savePack = () => {
    this.service.savePack(this.pack);
    this.segment = "counter";
  }

}

consumption.service.ts:

代码语言:javascript
复制
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import { pack } from './pack.interface';
import { consumption } from './consumption.interface';

@Injectable({
  providedIn: 'root'
})
export class ConsumptionService {

  constructor(private storage: Storage) { }

  getPack = () => {
    return new Promise((resolve, reject) => {
      this.storage.get("pack").then((pack) => {
        resolve(pack);
      })
    })
  }

  savePack = (pack: pack[]) => {
    this.storage.set("pack", pack);
  }

  getConsumptions = () => {
    return new Promise((resolve, reject) => {
      this.storage.get("consumption").then((kulutukset) => {
        resolve(kulutukset);
      })
    })
  }

  addConsumptions = (newconsumption: consumption) => {
    this.storage.get("consumption").then((data: consumption[]) => {
      let consumptions = data;
      let current_exists = false;
      if (consumptions == null) {
        consumptions = [{date: new Date().toLocaleDateString(), 
          consumption: 0, last_smoked: new Date().toLocaleTimeString()},
        ]
      }
      for (let consumption of consumptions) {
        // use current date
        if (consumption.date == newconsumption.date) {
          current_exists = true;
          consumption.date = newconsumption.date;
          consumption.consumption = newconsumption.consumption;
          consumption.last_smoked = newconsumption.last_smoked;
        }
      }
      // new date
      if (current_exists == false) {
        consumptions.push(newconsumption);
      }
      this.storage.set("consumption", consumptions);
    }
    )}

    saveConsumptions = (consumptions: consumption[]) => {
      this.storage.set("consumption", consumptions);
    }

}
EN

回答 2

Stack Overflow用户

发布于 2019-01-31 09:34:26

在Ionic中理解页面/组件的生命周期是很重要的;

  • 一旦组件被放置,在初始化所有其他东西之前调用构造函数;
  • 当加载组件/页面时,ngOnInit (OnInit角事件)称为一次性
  • 有一堆离子生命周期从盒子里冒出来,作为"ionViewDidLoad“、"ionViewWillLoad”等离子应用程序,它们有各种不同的行为,实际上可能适合你的需要。

由于Ionic应用程序实际上将一个页面堆叠在另一个页面上,以便将移动应用程序的标准行为与后退按钮等匹配起来(在浏览器devtools中检查应用程序的结构并尝试打开多个页面),正确的方法是挂在Ionic生命周期上,因为每次加载视图、重新打开应用程序或导航到页面时,都会触发ionViewDidLoadionViewWillLoad;事件。

在这里阅读更多信息:https://blog.ionicframework.com/navigating-lifecycle-events/

票数 3
EN

Stack Overflow用户

发布于 2019-01-31 07:23:13

在构造函数(){}中可以这样做。

代码语言:javascript
复制
data = [];
constructor(private storage: Storage) { 
  //write your code
  //for example:
  this.storage.get("pack").then((pack) => {
    this.data = pack;
  })
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54454894

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档