【问题标题】:Calling a variable from outside the function does not work javascript [duplicate]从函数外部调用变量不起作用javascript [重复]
【发布时间】:2018-08-31 12:11:37
【问题描述】:

谁能帮忙,,

所以我使用@ngx-pwa 将登录数据存储在称为登录的本地存储密钥中

我正在尝试获取此数据并显示它,但我无法定义!

public customerProfile

ngOnInit() {
 this.getProfileData();
 console.log(this.cutomerProfile) //shows undefined
}

getProfileData() {
 this.localStorage.getItem('login').subscribe((login) => {
   this.customerProfile = login;
   console.log(this.customerProfile.user) //shows login data
 })
}

【问题讨论】:

  • 那是因为getItem 是异步的,所以ngOnInit 试图在设置之前打印customerProfile
  • 所以我应该使用 afterViewInit() {} 还是我应该怎么做才能让它正确

标签: javascript angular typescript angular5


【解决方案1】:

问题是,此时您在ngOnInit() 上调用console.log() this.cutomerProfile 未设置,因为this.localStorage.getItem('login') 尚未准备好。

使用回调可能是您的解决方案:

public customerProfile

ngOnInit() {
 this.getProfileData(() => console.log(this.cutomerProfile));
}

getProfileData(cb) {
 this.localStorage.getItem('login').subscribe((login) => {
   this.customerProfile = login;
   console.log(this.customerProfile.user) //shows login data
   cb();
 })
}

你也可以使用 Promise:

public customerProfile

ngOnInit() {
 this.getProfileData().then(() => console.log(this.cutomerProfile));
}

getProfileData() {
  return new Promise((resolve, reject) => {
    this.localStorage.getItem('login').subscribe((login) => {
      this.customerProfile = login;
      console.log(this.customerProfile.user) //shows login data
      resolve();
    })
  });
}

【讨论】:

    【解决方案2】:

    如果您愿意,可以使用 Promiseasync/await 函数。

    public customerProfile;
    
    async ngOnInit() {
     this.customerProfile = await this.getProfileData();
      // The console.log (next line) will wait for the promise to be resolved.
      console.log(this.customerProfile);     }
    
    getProfileData() {
      return new Promise((resolve, reject) => {
        this.localStorage.getItem('login').subscribe((login) => {
          resolve(login);
        })
      });
    }
    

    【讨论】:

      【解决方案3】:

      记录 customerProfile 值的最简单解决方案是调用一个函数,该函数从异步的 this.localStorage.getItem() 中记录该变量,因此在它获取存储的项目后,它会调用该回调函数,如下所示:

      ngOnInit() {
       this.getProfileData();
      }
      
      getProfileData() {
       this.localStorage.getItem('login').subscribe((login) => {
         this.customerProfile = login;
         console.log(this.customerProfile.user) ;
         callback();
       })
      }
      
      callback(){
          console.log(this.cutomerProfile);
      }
      

      【讨论】:

      • AAAAaaaa l 7alawaaaa diiii :'D
      • 不客气,先生
      猜你喜欢
      • 2012-12-10
      • 1970-01-01
      • 1970-01-01
      • 2018-06-14
      • 1970-01-01
      • 2013-11-14
      • 2015-07-19
      • 1970-01-01
      • 2019-09-19
      相关资源
      最近更新 更多