Javascript 为什么本地存储的条件不起作用?
在模板组件AppComponent中,变量this.loggedInService.isLoggedIn根据值在登录和注销方法之间切换,应用程序组件AppComponent中的登录和注销方法在服务loggedInService中订阅这些方法,具体取决于方法,将变量的值更改为true或false 同样在Guard的方法checkLogin url:string中,我根据变量this.loggedInService.isLoggedIn的值返回true或false 一切正常,但当我重置页面时,我需要保留输入或输出按钮的值。我尝试在服务的login和logout方法中这样做,但是在重新加载页面后,更改仍然没有保存。帮助解决此问题,使更改在页面重新启动后保持不变 AppComponent的模板: {{this.loggedInService.isLoggedIn?'Exit':'Enter'}Javascript 为什么本地存储的条件不起作用?,javascript,angular,typescript,local-storage,storage,Javascript,Angular,Typescript,Local Storage,Storage,在模板组件AppComponent中,变量this.loggedInService.isLoggedIn根据值在登录和注销方法之间切换,应用程序组件AppComponent中的登录和注销方法在服务loggedInService中订阅这些方法,具体取决于方法,将变量的值更改为true或false 同样在Guard的方法checkLogin url:string中,我根据变量this.loggedInService.isLoggedIn的值返回true或false 一切正常,但当我重置页面时,我需要
我对你的密码有疑问 在LoggedInService onInit中,为什么要直接调用登录和注销
this.CheckAuthentication();
this.login();
this.logout();
这样做就是从本地存储中添加和删除。另外,您可以通过在浏览器控制台中键入localStorage来检查本地存储中的数据。我认为您应该注释或删除onInit方法,将isLoggedIn更改为基于localStorage项的get方法
export class LoggedinService implements OnInit {
redirectUrl: string;
constructor() {}
get isLoggedIn(): boolean {
return localStorage.getItem('login') ? true : false;
}
login(){
localStorage.setItem('login','true')
}
logout(){
localStorage.removeItem('login')
}
}
应用程序组件
removietem'login';为什么下一行的localStorage.getItem'login'会返回除null以外的任何内容?它看起来像是一个多线程的防护,但我认为它在多线程环境中不起作用;删除ngOnit不会改变任何内容除了在AppComponent html中引用this.loggedInService.isLoggedIn之外,您可以调用this.loggedInService。检查身份验证或在AppComponent ngOnInit中获取此值一次,并在AppComponent中存储为isLoggedIn变量从模板html中删除此值单击=this.loggedInService.isLoggedIn?注销:登录>{this.loggedInService.isLoggedIn?'Exit':'Enter'}}@IgorShvets让你更新appComponent=>this.loggedInService.logIn而不是登录和注销普通方法我这样做了吗?你能在StackBlitz中展示你的方法吗?如果你根据你的代码创建一个示例,那么我会更新它
export class AppComponent {
constructor(private loggedInService: LoggedinService,
private router: Router) {
}
logIn(): void {
this.loggedInService.login(); // set the state as login
let redirect = this.loggedInService.redirectUrl ? this.loggedInService.redirectUrl :
'/gallery';
this.router.navigate([redirect]);
}
logout(): void {
this.loggedInService.logout(); //// set the state as logout
this.router.navigate(['/']);
}
}