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

Calling a variable from outside the function does not work javascript

谁能帮忙,

所以我使用 @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
 })
}

问题是,目前您在 ngOnInit() this.cutomerProfile 调用 console.log() 未设置,因为 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();
    })
  });
}

如果需要,可以使用 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);
    })
  });
}

记录 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);
}