簡體   English   中英

如何不使用ngOnInit()在Angular中顯示數據?

[英]How to display data in Angular without ngOnInit()?

我在Ionic 4中有一個香煙計數器應用程序。請在此處Stackblitz: https ://stackblitz.com/edit/ionic-8xrdgo。 當用戶按下計數器細分中的“添加一個”按鈕時,我需要在歷史記錄細分中顯示最新的消費數據。 由於某些原因,需要重新加載應用程序才能在歷史記錄段中顯示最新數據。

重現該問題:

  1. 在不consumption存儲空間的情況下啟動應用程序
  2. 單擊添加一個按鈕。 新消耗已成功添加到存儲。
  3. 再次單擊“添加一個”按鈕。 現在應該更新現有的消耗量,但是由於某種原因沒有更新。 此外,歷史記錄段不會顯示數據。
  4. 重新加載應用程序。
  5. 單擊添加一個按鈕。 現在,現有消耗量已成功更新到存儲中,並且消耗量顯示在歷史記錄段中。

這里的問題是,必須重新加載應用程序才能將現有消耗量更新到存儲中並顯示出來。

完整代碼在這里:

home.page.html:

<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>

接口:

export interface pack {
    price: number,
    cigarettecount: number
}

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

home.page.ts:

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

}

消費。服務:

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

}

了解頁面/組件的生命周期在Ionic中的工作方式非常重要;

  • 一旦放置了組件,就在初始化所有其他組件之前調用構造函數。
  • 加載組件/頁面時,將ngOnInit(OnInit Angular事件)稱為ONCE
  • 對於任何Ionic應用程序,都有大量的Ionic生命周期,例如“ ionViewDidLoad”,“ ionViewWillLoad”等,它們具有各種不同的行為,實際上可能滿足您的需求

由於Ionic應用程序實際上將一頁堆疊在另一頁之上,以使移動應用程序的標准行為與后退按鈕和所有按鈕匹配(請在瀏覽器devtools中檢查應用程序的結構並嘗試打開多個頁面),因此正確的方法是掛起離子生命周期,如ionViewDidLoadionViewWillLoad 每次加載視圖,重新打開應用程序或導航到頁面時,都會觸發此事件。

在此處閱讀更多信息: https : //blog.ionicframework.com/navigating-lifecycle-events/

您可以在constructor(){}中進行

data = [];
constructor(private storage: Storage) { 
  //write your code
  //for example:
  this.storage.get("pack").then((pack) => {
    this.data = pack;
  })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM