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

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

问题描述

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

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

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

解决方案

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

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

可以在此处找到有关 *ngIf 的更多详细信息:

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

例如

@Component({选择器:'你的选择器',模板:`<div *ngIf='isLoggedIn() === true'><menu-component></menu-component><搜索组件></搜索组件><路由器插座></路由器插座>

<div *ngIf='isLoggedIn() !== true'><登录组件></登录组件>

`...})导出类 YourSelectorComponent {isLoggedIn() {//检查是否登录}}

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

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?

解决方案

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.

More details on *ngIf can be found here:

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

ex.

@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天全站免登陆