我是Ionic的新手,正在尝试使用本地存储,我的问题是以下问题...
我有一个登录表单,当登录过程成功时,它会将服务器响应中的一些数据存储到本地存储中,然后重定向到主页。当主页启动ngOnInit时,我正在尝试从本地存储中检索数据,并将其显示在Html文件上的变量call customerData上。但是在记录之后,应该显示用户数据的变量customerData首次为空,然后使用控制台日志查看该值显示为Undefined。
但是,在成功登录后,当我在本地存储中检查数据时,我需要的所有客户端信息都会存储在其中。
当我刷新页面时,它将显示所有内容。
我认为这与当我试图在页面上显示它以及刷新页面时所有就绪的localStorage上的值尚未准备好有关。
拜托我需要你的帮忙。我的代码如下。
登录名
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);
});
}
您应该在订阅内部进行导航,因为要在完成登录功能之前进行导航。请记住,订阅是一种异步方法。