简体   繁体   中英

Local Storage data returning Undefined or Null

I'm new to Ionic and I'm trying to use local storage, my problem is the following...

I have a login form, that when the login processes it's successful it stores some data from the server response to the local storage, and then redirects to the home page. When the home page starts the ngOnInit, I'm trying to retrieve the data from the local storage and display it on a variable call customerData on my Html file. But after logging, the variable customerData, which is supposed to display user data is blank at the first time and using the console log to see the value says Undefined.

But when I check the data in the local storage after the successful login all of the client info I need is stored and its there.

When I refresh the page it shows everything how it's supposed to be.

I think it has something to do with the values on the localStorage not being ready when I'm trying to display it on the page and when I refresh the page all is ready now.

Please I need your help. My code below.

login.ts

  loginForm(){
    this.platform.ready().then(() => {
      if((this.password != '') &&  (this.CFS.validateEmail(this.email))) {


        this.auth.loginCustomer(this.email,this.password).then((response) => {
        if(response['token']){

        console.log('Returned Token: ',response['token']);
        console.log('Returned user enamil: ',response['user_email']);   

          this.auth.getUserData(this.email).subscribe((userData) => {
          this.customerData =  userData;
           console.log('Customer Data: ', this.customerData);
          let currentUserId = this.customerData[0].id;
          localStorage.setItem('currentUserId', currentUserId);

          if(currentUserId){
            let found = localStorage.getItem('currentUserId');
            console.log('local storage id', found);
          }

           this.CFS.presentToast('Login successful', 'buttom',2000, 'success');


        });


          this.route.navigateByUrl('/home');

      } else {
        this.CFS.presentToast('Invalid username or password', 'buttom',2000,'danger');

      } 
    });
      } else {
        this.CFS.presentToast('Please fill  the form correctly', 'buttom',2000,'danger');

      }
    });

  }

home.ts

customerData: any ;
 ngOnInit() {  

      let isUserLoggedIn = localStorage.getItem('currentUserId');

      this.WC.getUserInfo(isUserLoggedIn).subscribe((data)=>{

        this.customerData = data;
        console.log('user data', this.customerData);
      }); 
}

You should to navigate inside your subscription, because you are navigating before complete the login function. Remember that subscriptions are an asynchronous methods.

So, when you arrive to the home.page, is posible that didn't save the data in the localStorage yet.

https://stackblitz.com/edit/ionic-64qb9r?file=app%2Fapp.component.ts

The function inside the subscribe method invocation is executed after receiving the server answer (asynchronously). So, the code to navigate to the home page executes before the code that executes after the server responds. You should move the this.route.navigateByUrl('/home'); line inside the subscribe callback method as follows:

 loginForm(){
    this.platform.ready().then(() => {
      if((this.password != '') &&  (this.CFS.validateEmail(this.email))) {


        this.auth.loginCustomer(this.email,this.password).then((response) => {
        if(response['token']){

        console.log('Returned Token: ',response['token']);
        console.log('Returned user enamil: ',response['user_email']);   

          this.auth.getUserData(this.email).subscribe((userData) => {
          this.customerData =  userData;
           console.log('Customer Data: ', this.customerData);
          let currentUserId = this.customerData[0].id;
          localStorage.setItem('currentUserId', currentUserId);

          if(currentUserId){
            let found = localStorage.getItem('currentUserId');
            console.log('local storage id', found);
          }

           this.CFS.presentToast('Login successful', 'buttom',2000, 'success');

           this.route.navigateByUrl('/home');

        });


      } else {
        this.CFS.presentToast('Invalid username or password', 'buttom',2000,'danger');

      } 
    });
      } else {
        this.CFS.presentToast('Please fill  the form correctly', 'buttom',2000,'danger');

      }
    });

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM