角4:用户状态
问题描述:
这里条件显示的问题是:角4:用户状态
我尽量遵循这个小教程,以便使一些有条件的显示在我的当前应用程序,这取决于用户的loggedIn状态。这里是链接:
https://loiane.com/2017/08/angular-hide-navbar-login-page/
它看起来很简单&高效。但是,我无法在当前的应用程序中使用它。继主教程指引,我来到这个代码:
*menu.component.ts:
authStatus: Observable<boolean>;
constructor(private authService: AuthService){
}
ngOnInit(){
this.authStatus = this.authService.isLoggedIn();
}
login(){
this.authService.login();
}
logout(){
this.authService.logout();
}
*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);
}
有人可以解释我做错了什么...?我在网上查了,但没有成功一些其他的例子......
感谢您的阅读/帮助
答
试试这个
login(){
this.authStatus = this.authService.login();
}
logout(){
this.authStatus = this.authService.logout();
}
从构造函数中删除,onint代码
答
编辑
这里是链接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
函数返回你可以在构造函数中认购的可观察的。无需在ngOnInit中添加this.authStatus = this.authService.isLoggedIn();
,因为然后this.authStatus将成为Observable的实例,而不是我们所需的布尔值。
为什么你分配2次this.authStatus在构造函数,oninit,目的是什么 –
猜测我错了“订阅部分”,这不是教程的一部分,你的评论是正确的,我删除了这一行。但这并不能解决问题.... – Julo0sS
不会从构造函数中删除订阅...从'ngOnInit'移除订阅 – Rahul