Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

angular - Angular2 CanActivate from beta to current RC3

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...