从函数外部调用变量不起作用

Oma*_*ady -2 javascript typescript angular angular5

有人可以帮忙吗

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

在这里,我正在尝试获取此数据并显示它但我未定义!

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
 })
}
Run Code Online (Sandbox Code Playgroud)

J. *_*adi 5

问题是,当你打电话给你的console.log()时候ngOnInit() 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();
 })
}
Run Code Online (Sandbox Code Playgroud)

你也可以使用一个承诺:

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();
    })
  });
}
Run Code Online (Sandbox Code Playgroud)