我在我的 Angular 5 应用程序中实现了导航栏显示/隐藏,用于用户登录/注销,这是我的参考
https://loiane.com/2017/08/angular-hide-navbar-login-page/
这在我的本地工作正常,但在部署时失败。可能是什么问题。我正在使用代码,只是做了一些微小的更改。
Auth Gard
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot):
Observable<boolean> {
return this.authService.isLoggedIn.pipe(
take(1),
map((isLoggedIn: boolean) => {
if (!isLoggedIn) {
this.router.navigate(['/login']);
return false;
}
return true;
})
);
}
认证服务
private loggedIn: BehaviorSubject<boolean> = new
BehaviorSubject<boolean>(false);
get isLoggedIn() {
this.login();
return this.loggedIn.asObservable();
}
constructor(private router: Router, private sessionService:
SessionService) {}
login() {
const userSession = this.sessionService.get('userEmail');
this.loggedIn.next(userSession !== null ? true : false);
}
logout() {
this.loggedIn.next(false);
this.router.navigate(['/login']);
}
标题组件
isLoggedIn$: Observable<boolean>;
userImage: string;
constructor(private sessionService: SessionService, private authService:
AuthService, private route: ActivatedRoute) {
this.route.params.subscribe(val => {
this.isLoggedIn$ = this.authService.isLoggedIn;
});
}
ngOnInit() {
this.isLoggedIn$ = this.authService.isLoggedIn;
const img = this.sessionService.get('userImage');
this.userImage = img === null ? '' : <string>img;
}
toggleMenu() {
this.showMenu = !this.showMenu;
console.log(this.showMenu);
}
标题 HTML
<ul class="header_main_nav condensed" *ngIf="isLoggedIn$.source._value">
<li class="routlink">
<a [routerLink]="['/agileBomRefLnk']" routerLinkActive="active">
<span class="glyphicon glyphicon-search"></span>
<span class="link-text">Agile BOM</span>
</a>
</li>
</ul>
以简单的方式,最少的改变
merge login component with AppComponent and put *ngIf on
<div *ngIf="!loginPage">
<app-header [(loginbutton)]="loginPage"></app-header><!-- [(loginbutton)] is an output to trigger the boolean "loginPage" -->
<router-outlet></router-outlet>
</div>
<div *ngIf="!loginPage">
LoginCode...
</div>
我希望对你有帮助......