I am taking my first steps with Angular 2 and angular in general, and I am wondering how to setup a landing page.
My goal is to show a landingpage everytime the user does not have a token in local storage or in a cookie.
My app.component.ts looks like this
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 seperate page that doesn't have access to the navbar. Which is what the user will always land on if he isn't logged in.
Would be awesome if someone could help me start out or atleast point me in a good direction, maybe point me to a good angular 2 tutorial.
This is the boilerplate I am basing my app on https://github.com/mgechev/angular2-seed
You can override the router-outlet and check on activation, if the token is present. Something like this:
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 extended to be able to work with roles and other access controlls.
You can just redirect to a specific route on load when the token is not available.
export class AppComponent {
constructor(private router:Router) {
if(!hasToken()) {
router.navigate(['/LoginForm']);
}
}
}
Alternatively you can create a custom RouterOutlet
that checks for each route if it is allowed for the user to navigate to that route like explained in http://www.captaincodeman.com/2016/03/31/angular2-route-security/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With