【问题标题】:Ionic 2 / Angular 2 - Getting undefined value from global variableIonic 2 / Angular 2 - 从全局变量中获取未定义的值
【发布时间】: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,而不是
  • 感谢您的解释!

标签: angular ionic2


【解决方案1】:

这是一个时间问题,你有两个异步调用,然后你有你的this.setRadioButton(),这个函数将在另外两个异步调用之前运行。

如果您想在 profile.ts:22 Check 1 Instructor 之后运行 this.setRadioButton(),让我们更改该代码以执行您想要的操作。

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);    
      this.setRadioButton(); // HERE, this is what you want.
   }).catch((c)=>console.log(c));

  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-27
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    相关资源
    最近更新 更多