Skip to content

Instantly share code, notes, and snippets.

@sonicoder86
Last active June 25, 2016 08:50
Show Gist options
  • Save sonicoder86/3dbfff1b1f787c28ade6eacc6f911d10 to your computer and use it in GitHub Desktop.
Save sonicoder86/3dbfff1b1f787c28ade6eacc6f911d10 to your computer and use it in GitHub Desktop.
Authentication in Angular 2 - part 4
// logged-in-router-outlet.ts
import {
ElementRef, DynamicComponentLoader, AttributeMetadata, Directive, Attribute
} from '@angular/core';
import { Router, RouterOutlet, ComponentInstruction } from '@angular/router-deprecated';
import { UserService } from './user.service';
@Directive({
selector: 'router-outlet'
})
export class LoggedInRouterOutlet extends RouterOutlet {
publicRoutes: Array;
private parentRouter: Router;
private userService: UserService;
constructor(
_elementRef: ElementRef, _loader: DynamicComponentLoader,
_parentRouter: Router, @Attribute('name') nameAttr: string,
private userService: UserService
) {
super(_elementRef, _loader, _parentRouter, nameAttr);
this.router = _parentRouter;
this.publicRoutes = ['', 'login', 'signup'];
}
activate(instruction: ComponentInstruction) {
if (this._canActivate(instruction.urlPath)) {
return super.activate(instruction);
}
this.router.navigate(['Login']);
}
_canActivate(url) {
return this.publicRoutes.indexOf(url) !== -1 || this.userService.isLoggedIn();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment