Angular 2中用于身份验证的好的模板策略 [英] Good template strategy for authentication in Angular 2

查看:86
本文介绍了Angular 2中用于身份验证的好的模板策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前已启动并运行了一个Angular 2应用,其外观如下:

I currently have an Angular 2 app up and running that looks as follows:

App.component在访问站点时被引导. App.component的模板具有所有组件标签(例如menu.component,search.component和router-out).

App.component is bootstrapped when visiting the site. The template for App.component has all component tags (for example menu.component, search.component and the router-outlet).

我基本上需要以下内容:当前,由于用户需要登录,因此将访问者直接重定向到登录"页面.他仍然可以看到菜单以及仅适用于已登录用户的所有组件.最好的策略是添加额外的模板层,以免登录的用户被重定向?

What I basically need is the following: currently a visitor is directly redirected to the Login page because the user needs to login. He is still able to see the menu and all components that are only there for logged in users. What would be the best strategy to add an extra template layer, so not logged in users get redirected?

推荐答案

我完成此操作的方法是使用* ngIf指令隐藏"那些元素,直到对用户进行身份验证为止.我在上面的隐藏"一词周围使用了引号,因为angular实际上并没有隐藏模板的那部分,它实际上根本没有渲染它,因此它不在DOM中.

The way that I've done it is to use the *ngIf directive to "hide" those elements until the user is authenticated. I use quotes around the word hide above because angular doesn't actually hide that part of the template, it actually doesn't render it at all so it's not in the DOM.

这意味着除非用户登录,否则只会显示您的登录屏幕.

That means that unless the user logs in, only your login screen will be rendered.

有关* ngIf的更多详细信息,可以在这里找到:

More details on *ngIf can be found here:

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
    }
}

这篇关于Angular 2中用于身份验证的好的模板策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆