Angular 2 Landing Page

I am taking the first steps with Angular 2 and Angular in general, and I am wondering how to set up the landing page.

My goal is to show the landing page every time a user doesn’t have a token in local storage or in a cookie.

My app.component.ts is as follows

import {Component} from 'angular2/core'; import {ROUTER_DIRECTIVES, RouteConfig} from 'angular2/router'; import {NavbarComponent} from './navbar.component'; import {LoaderComponent} from './loader.component'; import {NameListService} from '../shared/index'; import {HomeComponent} from '../+home/index'; import {AboutComponent} from '../+about/index'; @Component({ selector: 'g-app', viewProviders: [NameListService], templateUrl: 'app/components/app.component.html', directives: [ROUTER_DIRECTIVES, NavbarComponent, LoaderComponent] }) @RouteConfig([ { path: '/', name: 'Home', component: HomeComponent }, { path: '/about', name: 'About', component: AboutComponent } ]) export class AppComponent { } 

/ home and / about are also components, if I understand correctly. Now I would like to have a separate page that does not have access to the navigation bar. This is what the user will always land if he does not log in.

It would be great if someone could help me get started, or at least point me in a good direction, maybe point me to a good Angular 2 tutorial.

This is the template that I'm based on the app https://github.com/mgechev/angular2-seed

+6
source share
2 answers

You can redefine the router socket and check activation if a token is present. Something like that:

 import {Directive, Attribute, ElementRef, DynamicComponentLoader} from 'angular2/core'; import {Router, RouterOutlet, ComponentInstruction} from 'angular2/router'; @Directive({ selector: 'router-outlet' }) export class LoggedInRouterOutlet extends RouterOutlet { publicRoutes: any; private parentRouter: Router; constructor(_elementRef: ElementRef, _loader: DynamicComponentLoader, _parentRouter: Router, @Attribute('name') nameAttr: string) { super(_elementRef, _loader, _parentRouter, nameAttr); this.parentRouter = _parentRouter; } activate(instruction: ComponentInstruction) { if (!hasToken()) { this.parentRouter.navigateByUrl('/login'); } return super.activate(instruction); } } 

Adapted from here: https://github.com/auth0-blog/angular2-authentication-sample/blob/master/src/app/LoggedInOutlet.ts


This can be expanded to be able to work with roles and other access control.

+3
source

You can simply redirect to a specific route at boot when the token is unavailable.

 export class AppComponent { constructor(private router:Router) { if(!hasToken()) { router.navigate(['/LoginForm']); } } } 

Alternatively, you can create a custom RouterOutlet that checks each route if the user is allowed to navigate that route, as described in http://www.captaincodeman.com/2016/03/31/angular2-route-security/

+1
source

All Articles