Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 implement it, but i can't get it right.
I tried export class NavbarComponent implements CanActivate, routerCanActivate(){}, canActivate(){}. I'm stuck.

What changes are needed for CanActivate to work in current RC3?

import {CanActivate} from 'angular2/router';
import {tokenNotExpired, JwtHelper} from 'angular2-jwt'; 
...    
@CanActivate (()=>tokenNotExpired())
export class NavbarComponent{
...
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
931 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...