在登录组件中,我尝试将用户的电子邮件存储到本地存储中:
handleResponse(data){
this.Token.handle(data.access_token);
this.Auth.changeAuthStatus(true);
this.service.senddata(this.user);
localStorage.setItem('email',this.user.email);//this line is important
this.router.navigateByUrl('/profile');
}
在导航栏组件中,我正在尝试获取电子邮件,但它给我一个错误"Cannot set property 'email' of undefined"
viewUser(){
this.user.email=localStorage.getItem('email');
this.userService.getProfile(this.user).subscribe(data=>this.loggedInUser=data);
}
在服务器端一切正常,数据也存储在本地存储中。 我已经尝试了一切来全局存储用户,但注意到确实有效。
编辑:我正在尝试使用从登录掩码获得的用户的电子邮件,以使用另一个组件从服务器获取用户的所有信息。
似乎user
在调用viewUser()
时是未定义的。
在导航栏组件上,应确保用户至少初始化为空对象或具有某些默认属性/值的对象。如果有接口,你可以做这样的事情
user: User = {
email: undefined
}
首先定义user
。
user:User = new User
然后
viewUser(){
this.user.email=localStorage.getItem('email');
this.userService.getProfile(this.user).subscribe(data=>this.loggedInUser=data);
}