我正在尝试实现一个动态标头组件,该组件会根据用户角色进行更改。
这是我的标题组件
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
currentUser:any;
constructor(
) {
this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
}
ngOnInit() {
}
}
这是我的标题模板
<nav class="navbar navbar-default" >
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li class="menu_item" *ngIf="!currentUser"><a [routerLink]="['/login']"> Login </a></li>
<li class="menu_item" *ngIf="currentUser"><a [routerLink]="['/signin']">Logout</a></li>
</ul>
</div>
</nav>
但问题是
有人可以帮我吗?
答案 0 :(得分:2)
您需要让HeaderComponent知道身份验证状态已更改。你可以使用一个observable:
在isAuthenticated$
AuthService
可观察对象
在HeaderComponent中注入该服务,并使用模板内的isAuthenticated$
,使用异步管道
在该observable上调用next()
以触发更改
这样的事情应该可以胜任:
class AuthService {
isAuthenticated$ = new BehaviorSubject<boolean>(false);
constructor() {
const authenticated = !!JSON.parse(localStorage.getItem('currentUser'));
this.isAuthenticated$.next(authenticated);
}
login() {
this.isAuthenticated$.next(true);
}
logout() {
this.isAuthenticated$.next(false);
}
}
标头组件控制器:
class HeaderComponent implements OnInit {
public currentUser: any;
public isAuthenticated$ = this.auth.isAuthenticated$;
private (private auth: AuthService) {}
ngOnInit() {
this.isAuthenticated$.subscribe(authenticated => {
if (authenticated) {
this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
} else {
this.currentUser = null;
}
});
}
}
您的模板:
<nav class="navbar navbar-default" >
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li class="menu_item" *ngIf="!(isAuthenticated$ | async)"><a [routerLink]="['/login']"> Login </a></li>
<li class="menu_item" *ngIf="(isAuthenticated$ | async) && currentUser.someField === 'someValue'"><a [routerLink]="['/signin']">Logout</a></li>
</ul>
</div>
</nav>
答案 1 :(得分:0)
请使用ng-template
` <ul class="navbar-nav">
<ng-template #anonymousUser>
<li class="nav-item">
<a class="nav-link" routerLink="/login">Login</a>
</li>
</ng-template>
<li ngbDropdown *ngIf="appUser ;else anonymousUser " class="nav-item dropdown ">
<a ngbDropdownToggle class="nav-link dropdown-toggle" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{{appUser.name}}</a>
<div ngbDropdownMenu class="dropdown-menu " aria-labelledby="dropdown01">
<a class="dropdown-item" routerLink="/my/orders">My Orders</a>
<ng-container *ngIf="appUser.isAdmin">
<a class="dropdown-item" routerLink="/admin/orders">Manage Order</a>
<a class="dropdown-item" routerLink="/admin/products">Manage Products</a>
</ng-container>
<a class="dropdown-item" (click)=logOut()>Log Out</a>
</div>
</li>
</ul>`