-2

can anyone help ,,

so i have stored login data in a local storage key called login using @ngx-pwa

here i'm trying to get this data and display it but i'm getting undefined!

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
 })
}
Shanil Arjuna
  • 1,135
  • 10
  • 18
Omar Abdelhady
  • 1,528
  • 4
  • 19
  • 31

3 Answers3

5

The Problem is, that at the moment you call your console.log() at ngOnInit() this.cutomerProfile is not set, because this.localStorage.getItem('login') isn't ready.

Using a callback could be a solution for you:

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();
 })
}

you could use a promise, too:

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();
    })
  });
}
jsadev.net
  • 2,800
  • 1
  • 16
  • 28
3

If you want that you can by using Promise and async/await function.

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);
    })
  });
}
Disfigure
  • 720
  • 6
  • 19
0

the simplest solution to log the value of customerProfile is to call a function that log that variable from the this.localStorage.getItem() which is async, so after it gets the stored item, it calls that callback function like this:

ngOnInit() {
 this.getProfileData();
}

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

callback(){
    console.log(this.cutomerProfile);
}