在Angular 7应用程序中,我有几个组件必须根据用户是否通过身份验证或是否具有特定声明而必须显示/隐藏内容...
export class UserProfileComponent implements OnInit {
constructor(private authService: AuthService) { }
ngOnInit() {
}
}
我有一个AuthService,如下:
export class AuthService {
hasClaim(claim: Claim) : boolean { }
isSignedIn(): boolean { }
// Other methods
}
基于身份验证来显示/隐藏视图HTML部分的最佳方法是什么?
答案 0 :(得分:0)
您可以在使用该视图的组件中创建服务的实例,而只需使用<div *ngIf="yourcomponent.serviceInstance.isSignedIn()"></div>
。如果我没记错,尽管以前的方法也不错。
答案 1 :(得分:0)
我认为@ Jaime_c7方法不起作用,因为该服务在构造函数中设置为私有,并且无法从component.ts文件外部调用,这就是我在原始注释中进行设置的原因。
在您的html中:
<div *ngIf="checkIsSignedIn()">Whatever you are showing or hiding</div>
component.ts:
export class UserProfileComponent implements OnInit {
constructor(private authService: AuthService) { }
ngOnInit() {
}
checkIsSignedIn() {
this.authService.isSignedIn();
}
答案 2 :(得分:0)
您可以在ngOnInit()
中添加要显示或隐藏的组件的身份验证检查。
像这样:
export class UserProfileComponent implements OnInit {
visible: boolean = true;
constructor(private authService: AuthService) { }
ngOnInit() {
this.visible = this.authService.isSignedIn();
}
}
并在模板的顶级父div中添加*ngIf = "visible"
。
答案 3 :(得分:0)
我们曾担任过用户角色,并且通过使用指令,我喜欢以下 approach 。您可以根据需要修改指令。这是该基于角色的代码的更新版本:
@Directive({selector: '[appIfRole]'})
export class IfRoleDirective {
user$ : Subscription;
@Input("appIfRole") roleName : string;
constructor( private templateRef : TemplateRef<any>,
private viewContainer : ViewContainerRef,
private authService : AuthService ) { }
ngOnInit() {
// returns current user
this.user$ = this.authService.user.pipe(
tap(() => this.viewContainer.clear()),
filter(user => user.role === this.roleName)
)
.subscribe(() => this.viewContainer.createEmbeddedView(this.templateRef);)
}
ngOnDestroy() {
this.user$.unsubscribe();
}
}
然后这很容易使用,例如:
<div *appIfRole="'admin'">
Only for Admin
</div>
因此,这里有一个基本概念,您可以根据需要修改该指令。