I\'m trying to implement in Angular2, the Auth0 login method from this video. He is also using angular2-jwt
.
I read the documentation, tried to implemen
See
Create a service class that acts as guard:
import { CanActivate } from '@angular/router'; export class AuthGuard implements CanActivate { canActivate() { console.log('AuthGuard#canActivate called'); return true; } }
In the new router this now supports dependency injection out of the box
Configure the route to use that guard:
{ path: 'admin', component: CrisisAdminComponent, canActivate: [AuthGuard] },
The guard service can also return an observable that resolves to true or false
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/delay'; @Injectable() export class AuthService { isLoggedIn: boolean = false; login() { return Observable.of(true).delay(1000).do(val => this.isLoggedIn = true); } logout() { this.isLoggedIn = false; } }
The guard service needs to be provided as any other service.
A good place would be for example APP_ROUTER_PROVIDERS
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes),
AuthGuard
];