Angular2 CanActivate from beta to current RC3

前端 未结 1 1513
一向
一向 2020-12-18 14:21

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

相关标签:
1条回答
  • 2020-12-18 15:02

    See

    • https://angular.io/docs/ts/latest/guide/router.html#!#can-activate-guard
    • https://angular.io/docs/ts/latest/guide/router.html#!#can-deactivate-deactivate

    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
    ];
    
    0 讨论(0)
提交回复
热议问题