Good template strategy for authentication in Angular 2

怎甘沉沦 提交于 2019-12-05 18:16:31

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/37100271/good-template-strategy-for-authentication-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!