【问题标题】:Good template strategy for authentication in Angular 2Angular 2 中用于身份验证的良好模板策略
【发布时间】:2016-05-08 13:17:16
【问题描述】:

我目前有一个 Angular 2 应用程序正在运行,如下所示:

App.component 在访问该站点时被引导。 App.component 的模板包含所有组件标签(例如 menu.component、search.component 和 router-outlet)。

我基本上需要的是以下内容:当前访问者直接重定向到登录页面,因为用户需要登录。他仍然能够看到菜单和只有登录用户才能看到的所有组件。添加一个额外的模板层以使未登录的用户被重定向的最佳策略是什么?

【问题讨论】:

    标签: angular angular2-routing angular2-template


    【解决方案1】:

    我的做法是使用 *ngIf 指令“隐藏”这些元素,直到用户通过身份验证。我在上面的隐藏一词周围使用引号,因为角度实际上并没有隐藏模板的那部分,它实际上根本没有渲染它,所以它不在 DOM 中。

    这意味着除非用户登录,否则只会呈现您的登录屏幕。

    关于 *ngIf 的更多细节可以在这里找到:

    https://angular.io/docs/ts/latest/guide/structural-directives.html#!#ngIf

    例如

    @Component({
        selector: 'your-selector',
        template: `
            <div *ngIf='isLoggedIn() === true'>
                <menu-component></menu-component>
                <search-component></search-component>
                <router-outlet></router-outlet>
            </div>
            <div *ngIf='isLoggedIn() !== true'>
                <login-component></login-component>
            </div>
        `
        ...
    })
    export class YourSelectorComponent {
        isLoggedIn() {
            //check if logged in
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-03
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      • 2011-05-12
      • 2017-05-20
      • 2019-03-23
      • 1970-01-01
      • 2020-02-25
      相关资源
      最近更新 更多