【发布时间】:2018-01-16 00:27:19
【问题描述】:
我面临一个奇怪的问题,我在一个全局变量中未定义,我想稍后使用它。我放了 2 个 console.log(),棘手的部分是 Check 2 (作为 console.log 输出)首先触发而不是 Check 1 )。请查看 TS 文件。在检查 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
【问题讨论】:
-
这是因为 this.profileType 是在异步上下文中定义的,所以在检查 1 中您会看到它打印,因为 console.log 在您可以访问它的承诺中,检查 2,而不是
-
感谢您的解释!