我有一个登录方法,该方法返回一个用户对象,可以使用依赖注入在所有组件之间共享该对象。
login(usuario: Usuario) {
this.http.post<Usuario>(this.baseUrl, {
username: usuario.username,
clave: usuario.clave
}).subscribe(data => {
if (data != null) {
localStorage.setItem('isLoggedIn', 'true');
localStorage.setItem('token', btoa(usuario.username + ':' + usuario.clave));
this.usuario2 = data;
this.router.navigate(['/buscador']);
} else {
alert('Authentication failed.');
}
});}
问题在于,如果我重新加载页面,则对象实例将刷新,其余组件将无法访问该对象实例。登录时,我尝试使用localStorage将整个对象设置为json字符串,然后在要使用它们的组件中解析它。这对所有组件都有效,除了只能在Init上访问的AppComponent之外。因此,我想知道对这种情况最好的方法是什么。