我已经有一个Angular 2应用程序,该应用程序已将身份验证集成到使用 service >。用户可以登录,当 localStorage 中有一个令牌时,用户被视为身份验证。我在Navbar中有一个按钮登录,可以提出模态登录表单。使用表单对用户进行身份验证后,它已关闭,但是该按钮不会更改为注销按钮。我已经将其设置为使用app.component
上的属性,称为IsAuthenticated
,该属性从身份验证服务isAuthenticated()
方法中获取其值,该方法可返回可观察到的布尔值类型,以指示用户是否已认证。但是,即使状态已更改,该属性也不会改变。我已经尝试了很多事情来使此响应状态更改,但是什么都没有用。任何帮助都将受到赞赏!
authentication.service.ts
(只是iSauthenticated函数):
public isAuthenticated(): Observable<boolean> {
let token = localStorage.getItem('currentUser');
if (token) {
let tokenObject = JSON.parse(token);
let expiresOn = moment(tokenObject.expires);
// Confirm there is a token, and it's expiration is later than now
let isLoggedIn = tokenObject.token !== '' && expiresOn > moment();
return Observable.of(isLoggedIn);
}
return Observable.of(false);
}
app.component.ts
:
export class AppComponent implements OnInit {
public IsAuthenticated: boolean;
loginModal: LoginComponent;
constructor (
private modalService: NgbModal,
private authService: AuthenticationService
) { }
openLogin(): void {
this.modalService.open(LoginComponent, { size: 'sm' });
}
logout(): void {
if (confirm('Are you sure you want to log out?')) {
this.authService.logout();
this.IsAuthenticated = false;
}
}
ngOnInit() {
this.authService.isAuthenticated()
.subscribe(loggedIn => this.IsAuthenticated = loggedIn);
}
}
app.component.html
:
<ul class="nav navbar-nav pull-right">
<li class="nav-item">
<button class="btn btn-primary" (click)="openLogin()" *ngIf="!IsAuthenticated">Login</button>
<button class="btn btn-primary" (click)="logout()" *ngIf="IsAuthenticated">Logout</button>
</li>
</ul>
当用户单击" 登录"按钮时,模态弹出,我可以登录,但是完成后,仍显示登录按钮,而不是注销,我有其他UI使用相同的ngIf
的元素也不会更改...我缺少什么?
编辑
将 *ngIf="isAuthenticated"
更改为 *ngIf="authService.isAuthenticated()"
,iSauthenticated是一个函数,因此您必须通过添加括号来称呼它,并且它是您服务的函数,因此您也必须调用服务的实例。