Angular 2 Cancelling Route Navigation on UnAuthenticate

前端 未结 3 2029
星月不相逢
星月不相逢 2021-01-16 09:27

I have an app, with 3 links: Home (/), Sign in (/user/sign-in) and User Detail (/user).

When user click Home, my app will be show content public

When user cl

3条回答
  •  忘掉有多难
    2021-01-16 10:05

    I think you could extend router outlet to implement such processing. Something like this:

    @Directive({
      selector: 'auth-outlet'
    })
    export class AuthOutlet extends RouterOutlet {
      publicRoutes: any;
      private parentRouter: Router;
      private authService: AuthService;
      constructor(_elementRef: ElementRef, 
                _loader: DynamicComponentLoader, 
               _parentRouter: Router,
               @Attribute('name') nameAttr: string, 
               _authService: AuthService) {
        (...)
      }
    
      activate(oldInstruction: ComponentInstruction) {
        var url = this.parentRouter.lastNavigationAttempt;
        console.log('attemping to nav');
        if (!this.publicRoutes[url] && !this.authService.loggedIn){
          var newInstruction = new ComponentInstruction('Login', [], new RouteData(), Login, false, 1);
          return super.activate(newInstruction);
        } else {
          return super.activate(oldInstruction);
        }
      }
    }
    

    The activate method is called when a route will be displayed. You can add at this level your processing.

    You use this directive this way un your template:

    @Component({
      (...)
      template: '',
      directives: [ AuthOutlet ]
    })
    (...)
    

    See these links for more details:

    • Angular 2 Authentication with child routes
    • https://auth0.com/blog/2016/01/25/angular-2-series-part-4-component-router-in-depth/

    Another option is to use the CanActivate decorator but it's per component and can't be applies globally.

提交回复
热议问题