我目前面临的问题是,从功能上讲,当用户登录时,我的导航栏不会自动更新以向他们显示正确的链接。仅当我手动刷新不需要的页面时,它才会更新,因为这是单页面应用程序。我可以正常处理注销,因为注销按钮和功能位于控制导航栏的组件内。但是,登录是通过身份验证服务控制的,对我的组件不可见。我尝试过制作isLoggedIn
boolean public,然后将组件导入到身份验证服务中,并在登录时将值设置为 true,但这会产生非描述性的 zone.js 错误。请参阅下文 - 感谢所有帮助。
app.component
它控制我的导航栏:
export class AppComponent implements OnInit{
private isLoggedIn: boolean;
constructor(private router: Router, private authenticationService: AuthenticationService) { }
ngOnInit() {
this.isLoggedIn = this.authenticationService.isLoggedIn();
}
logout() {
this.isLoggedIn = false;
this.authenticationService.logout();
this.router.navigate([""]);
}
title = 'MYlestone';
}
and the app.component
模板:
<div class="site-container">
<nav class="navbar navbar-toggleable-md">
<div *ngIf="isLoggedIn">
<span class="navbar-brand text-color">MYlestone</span>
</div>
<div *ngIf="!isLoggedIn">
<span class="navbar-brand text-color" [routerLink]="['']" style="cursor:pointer">MYlestone</span>
</div>
<div>
<div class="navbar-nav" *ngIf="isLoggedIn">
<a class="nav-item nav-link" href="#" [routerLink]="['content']">My Content</a>
<a class="nav-item nav-link" href="#" [routerLink]="['about']">About</a>
<div class="ml-auto">
<a class="nav-item nav-link" href="#" (click)="logout()">Logout</a>
</div>
</div>
</div>
</nav>
<div class="container-fluid text-color">
<!-- let client side routing take over, see app.routing.ts -->
<router-outlet></router-outlet>
</div>
</div>
如你看到的,isLoggedIn
在 ngOnInit 方法中设置[正确],并且当单击注销按钮时我的组件会适当更新。我正在努力弄清楚如何更新isLoggedIn
当用户登录时,此组件中的布尔值发生在执行此组件的 ngOnInit 方法之后。以防万一,您可以在下面找到authentication.service,它负责实际登录用户:
@Injectable()
export class AuthenticationService {
constructor(private http: Http) { }
login(email: string, password: string) {
return this.http.post('http://localhost:36000/api/accounts/authenticate', { email: email, password: password })
.map((response: Response) => {
let user = response.json();
if (user && user.token) {
localStorage.setItem('currentUser', JSON.stringify(user));
}
});
}
logout() {
localStorage.removeItem('currentUser');
}
isLoggedIn() {
//check to see if token exists
if (localStorage.getItem('currentUser')) {
return true;
}
else {
return false;
}
}
}