简体   繁体   English

本地存储数据返回 Undefined 或 Null

[英]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...我是 Ionic 的新手,我正在尝试使用本地存储,我的问题如下......

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.当主页启动 ngOnInit 时,我试图从本地存储中检索数据并将其显示在我的 Html 文件上的一个名为 customerData 的变量上。 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.但是在记录之后,应该显示用户数据的变量 customerData 第一次是空白的,并且使用控制台日志查看值显示为未定义。

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.我认为这与我尝试在页面上显示它时 localStorage 上的值未准备好有关,当我刷新页面时,现在一切都准备好了。

Please I need your help.拜托我需要你的帮忙。 My code below.我的代码如下。

login.ts登录.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主页.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.您应该在订阅中导航,因为您在完成登录 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.因此,当您到达主页时,可能尚未将数据保存在 localStorage 中。

https://stackblitz.com/edit/ionic-64qb9r?file=app%2Fapp.component.ts 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). subscribe方法调用里面的function在接收到服务器应答后(异步)执行。 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');你应该移动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');

      }
    });

  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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