Ionic 2 / Angular 2 - 从全局变量

时间:2018-01-15 16:19:28

标签: angular ionic2

我面临一个奇怪的问题,我在一个全局变量中未定义,我想稍后使用它。我已经放了2个console.log(),棘手的部分是Check 2(作为console.log输出)首先触发而不是Check 1)。请查看TS文件。在Check 1中,我得到了正确的值,但它在setRadioButton方法之后触发,我很困惑为什么会发生这种情况?

import { Component } from '@angular/core';
;import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ToastController } from 'ionic-angular';
import { NativeStorage } from '@ionic-native/native-storage';
@Component({
  selector: 'page-profile',
  templateUrl: 'profile.html'
})
export class ProfilePage {
  userImg : any;
  userName : string;
  profileType :string;
  instr : boolean;
  stud :boolean;
  constructor(public navCtrl: NavController, private nativeStorage : NativeStorage) {
    this.nativeStorage.getItem("userLogin").then((data)=>{
       this.userImg = data.picture;
       this.userName = data.name;
    }).catch((c)=>console.log(c));
    this.nativeStorage.getItem("userProfile").then((data)=>{
      this.profileType = data.userProfileType; 
      console.log("Check 1",this.profileType);    
   }).catch((c)=>console.log(c));
   this.setRadioButton()
  }

  setRadioButton()
  {
    console.log("Check 2",this.profileType); 
    if(this.profileType == "Instructor")
    {
      this.instr = true;
      console.log("I")
    }
    if(this.profileType == "Student"){
      this.stud = true;
      console.log("S")
    }
  }
}

控制台日志输出

FCMPlugin.js: is created
FCMPlugin.js:41 FCMPlugin Ready OK
bootstrap.js:10 Ionic Native: deviceready event fired after 1822 ms
index.js:411 DEVICE READY FIRED AFTER 1738 ms
profile.ts:29 Check 2 undefined
profile.ts:22 Check 1 Instructor

1 个答案:

答案 0 :(得分:1)

这是一个调整问题,你有两个异步调用然后你有file_task,这个函数将在其他两个异步调用之前运行。

如果您想在个人资料后运行this.setRadioButton():22检查1个教师,让我们更改该代码以执行您想要的操作。

this.setRadioButton()
相关问题