首页 文章

Angular 2:创建一个全局的,可设置的,可观察的属性?

提问于
浏览
0

我've got an Angular 2 app (using v2.1.0) with an authentication service to allow the user to login and logout of the app. I want to create a globally available boolean property that can be set when a user logs in or logs out so I can easily show and hide parts of the UI based on the state of the user. Something like isAuthenticated would be fine. However, I' m不完全确定创建全局类/服务的最佳方法是什么,或推荐的方法是什么 . 我找到了this问题,它确实解决了这个问题,但所有的答案都是在最终版本发布之前完成的,我相信它已经过时了 . 目前我在每个组件上都有一个属性,我需要跟踪返回到身份验证服务的登录状态,但对我来说似乎效率低下:

IsAuthenticated: boolean = this.authService.isAuthenticated();

3 回答

  • 0

    您可以尝试使用* ngIf添加或删除元素|隐藏或显示元素的可见性

    <div *ngIf="IsAuthenticated">Content</div> //add or remove
    
    <div [class.hidden]="!IsAuthenticated">Show with class</div> //show or hide
    

    更多细节https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ngIf

  • 0

    向服务添加布尔属性,并将其默认为false . 当用户登录时将其设置为true . 在服务中创建一个函数以返回布尔值 . 然后就像调用登录功能一样调用它 .

    服务是单身人士,做你想要的 .

  • 0

    首先,您需要在app.module提供程序上声明您的authService . 所有应用程序的1个authService实例 .

    接下来你可以这样做:

    <a *ngIf="!authService.isAuthenticated()" [routerLink]="['/login']">Login</a>
    

相关问题