当app第一次运行时,如何在离子中执行某些操作?

时间:2017-06-29 07:24:47

标签: ionic-framework ionic2

我正在尝试在第一次执行我的应用程序时运行一堆命令。我发现了一些代码,但它们似乎都不适合我。这就是我现在所拥有的:

  var applaunchCount = this.storage.get('launchCount');
  console.log(applaunchCount);

    if(applaunchCount){
          this.hello="succesive";
     }else{
    storage.set('launchCount','1');
        this.hello="first";
    }

我在我的Android设备上尝试过,hello的值始终保持“成功”。 编辑: home.ts文件是第一页

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { FormBuilder, Validators } from '@angular/forms';
import {cloths} from '../defaults.component';
import { Storage } from '@ionic/storage';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})


export class HomePage {
hello : string;
clothes=cloths;
l : string ;
public loginForm = this.fb.group({
    new: ["", ]

  });


  constructor(public navCtrl: NavController, public fb:FormBuilder, public storage:Storage) {
  var applaunchCount = this.storage.get('launchCount');
  var app : string;
  console.log(applaunchCount);

    if(applaunchCount){
    //This is a second time launch, and count = applaunchCount
          this.hello="succesive";
     }else{
    //Local storage is not set, hence first time launch. set the local storage item
    storage.set('launchCount','1');
        this.hello="first";
     //Do the other stuff related to first time launch
    }

  }
  buttonLogin(){

    this.clothes.push(this.loginForm.get('new').value);


  }


}

1 个答案:

答案 0 :(得分:0)

从存储中获取数据是async操作,因此您必须等到数据准备好后再使用它:

constructor(public navCtrl: NavController, public fb:FormBuilder, public storage:Storage) {

    let app : string; // <- You can use let instead of var here

    this.storage.get('launchCount').then(applaunchCount => { // <- Wait for the data to be ready

        // Now the data from the storage is ready!

        console.log(applaunchCount);

        if(applaunchCount) {
            // This is a second time launch, and count = applaunchCount
            this.hello = "succesive";
        } else {
            // Local storage is not set, hence first time launch. set the local storage item
            storage.set('launchCount','1');

            this.hello = "first";

            // Do the other stuff related to first time launch
        }
    });

}