我想记住变量loggedIn
的值,因为appComponent.html
中相应函数的值取决于它的值。请告诉我如何实现它?
应用程序组件团队:
<li class="nav-item">
<a class="btn btn-outline-success"
[class.btn-outline-success]="!this.loggedInService.loggedIn"
[class.btn-outline-danger]="this.loggedInService.loggedIn"
(click)="this.loggedInService.loggedIn ? logout() : logIn()">
{{this.loggedInService.loggedIn? 'Exit' : 'Enter'}}
</a>
</li>
应用程序组件代码:
export class AppComponent implements OnInit {
constructor(private loggedInService: LoggedinService,
private router: Router) {
}
ngOnInit() {
}
logIn(): void {
this.loggedInService.login();
if (this.loggedInService.loggedIn) {
let redirect = this.loggedInService.redirectUrl ? this.loggedInService.redirectUrl :
'/gallery';
this.router.navigate([redirect]);
}
}
logout(): void {
this.loggedInService.logout();
this.router.navigate(['/']);
}
}
LoggedinService:
export class LoggedinService implements OnInit {
redirectUrl: string;
loggedIn: boolean = false;
constructor() {}
ngOnInit(): void {}
login(): boolean {
localStorage.setItem('login', 'true');
return this.loggedIn = true;
}
logout(): boolean {
localStorage.removeItem('login');
return this.loggedIn = false;
}
}
答案 0 :(得分:3)
答案 1 :(得分:1)
用户登录https://{prefix}.visualstudio.com/{suffix}
的{{1}}方法后,您已经存储了login
。
现在,即使您重新加载页面,也可以使用以下命令从那里获取它:
LoggedinService
如果用户在重新加载页面之前已登录,它将返回“ true”。
然后您可以创建以下类:
login
然后在您的app.component.html中使用// Add this property in your app.component.ts
loggedIn = localStorage.getItem('login');
这样的语法动态使用这些类:
.btn-outline-success {
background: 'green';
}
.btn-outline-danger {
background: 'green';
}
答案 2 :(得分:1)
npm install @ngx-pwa/local-storage@6
npm install @ngx-pwa/local-storage@5
将此添加到您的应用模块:
imports: [
LocalStorageModule,
//other module imports here
],
export class LoggedinService implements OnInit {
redirectUrl: string;
loggedIn: boolean = false;
constructor(private localStorage: LocalStorage) {}
ngOnInit(): void {}
login(): boolean {
this.localStorage.setItem('login', 'true').subscribe(res => {
this.loggedIn = true;
});
return this.loggedIn = true;
}
logout(): boolean {
this.localStorage.removeItem('login').subscribe(res => {
this.loggedIn = false;
});
return this.loggedIn = false;
}
}
别忘了添加导入
import { LocalStorage } from "@ngx-pwa/local-storage";
检查存储库here