问题在于:
我尝试按照这个小教程,在我当前的应用程序中进行一些条件显示,具体取决于用户登录状态。这是链接:
https://loiane.com/2017/08/angular-hide-navbar-login-page/
它看起来很简单&高效。但是,我无法在我当前的应用程序中使用它。遵循主要教程指南,我来到这段代码:
top-menu.component.ts:
authStatus: Observable<boolean>;
constructor(private authService: AuthService){
}
ngOnInit(){
this.authStatus = this.authService.isLoggedIn();
}
login(){
this.authService.login();
}
logout(){
this.authService.logout();
}
top-menu.component.html:
<li><span (click)="login()">LOGIN</span></li>
<li><span (click)="logout()">LOGOUT</span></li>
//...
<li *ngIf="authStatus | async"><a [routerLink]="['/login']">CONDITIONAL LOGIN</a></li>
<li *ngIf="!authStatus | async"><a [routerLink]="['/logout']">CONDITIONAL LOGOUT</a></li>
auth.service.ts:
public loggedIn = new BehaviorSubject<boolean>(false);
get isLoggedIn(){
return this.loggedIn.asObservable();
}
login(){
this.loggedIn.next(true);
}
logout(){
this.loggedIn.next(false);
}
任何人都可以解释一下我做错了什么吗?我在互联网上检查了一些其他的例子,但没有成功......
感谢您阅读/帮助
答案 0 :(得分:0)
试试这个
login(){
this.authStatus = this.authService.login();
}
logout(){
this.authStatus = this.authService.logout();
}
从构造函数中移除onint代码
答案 1 :(得分:0)
修改强>
以下是plunkr
的链接authStatus: boolean;
subscription: Subscription;
constructor(private authService: AuthService){
this.subscription = this.authService.isLoggedIn().subscribe(result => {
this.authStatus = result;
});
}
ngOnInit(){
// this.authStatus = this.authService.isLoggedIn();
}
login(){
this.authService.login();
}
logout(){
this.authService.logout();
}
当您点击退出/登录时,相应的状态将在this.authStatus
中更新,并且可以轻松绑定到HTML
isLoggedIn
函数返回可以在构造函数中订阅的observable。无需在ngOnInit中添加this.authStatus = this.authService.isLoggedIn();
因为那么this.authStatus将成为Observable的实例而不是我们需要的布尔值。