2017-10-05 57 views
0

这里条件显示的问题是:角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); 
} 

有人可以解释我做错了什么...?我在网上查了,但没有成功一些其他的例子......

感谢您的阅读/帮助

+0

为什么你分配2次this.authStatus在构造函数,oninit,目的是什么 –

+0

猜测我错了“订阅部分”,这不是教程的一部分,你的评论是正确的,我删除了这一行。但这并不能解决问题.... – Julo0sS

+0

不会从构造函数中删除订阅...从'ngOnInit'移除订阅 – Rahul

回答

0

试试这个

login(){ 
    this.authStatus = this.authService.login(); 
} 

logout(){ 
    this.authStatus = this.authService.logout(); 
} 

从构造函数中删除,onint代码

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函数返回你可以在构造函数中认购的可观察的。无需在ngOnInit中添加this.authStatus = this.authService.isLoggedIn();,因为然后this.authStatus将成为Observable的实例,而不是我们所需的布尔值。

+0

top-menu.component.ts,@订阅线,我得到这个错误:无法调用其类型缺少呼叫签名的表达式。类型'Observable '没有兼容的呼叫签名。 – Julo0sS

+0

你是否从'rxjs/Subscription'导入了'import {Subscription};'? – Rahul

+0

同样的错误...当然,我没有导入订阅。我上面的代码是一个简化的示例。我的服务功能签名是这样的:登录(用户名:字符串,密码:字符串):Observable Julo0sS