Redirect to a different component inside @CanActivate in Angular2

前端 未结 6 559
攒了一身酷
攒了一身酷 2020-12-03 10:03

Is there any way we can redirect to a different component from @CanActivate in Angular2 ?

6条回答
  •  时光取名叫无心
    2020-12-03 10:29

    Yes, you can! Doing this will prevent your component from instantiating for nothing.

    First, make a new file src/app-injector.ts

    let appInjectorRef;
    
    export const appInjector:any = (injector = false) => {
        if (!injector) {
            return appInjectorRef;
        }
    
        appInjectorRef = injector;
    
        return appInjectorRef;
    };
    

    Then, get the reference from bootstrap

    // ...
    import {appInjector} from './app-injector';
    // ...
    
    
    bootstrap(App, [
      ROUTER_PROVIDERS
    ]).then((appRef) => appInjector(appRef.injector));
    

    Finally in your function

    // ...
    import {appInjector} from './app-injector';
    // ...
    
    @CanActivate((next, prev) => {
      let injector = appInjector();
      let router = injector.get(Router);
    
      if (42 != 4 + 2) {
        router.navigate(['You', 'Shall', 'Not', 'Pass']);
        return false;
      }
    
      return true;
    })
    

    Et voilà !

    It was discussed here https://github.com/angular/angular/issues/4112

    You can find a complete example here http://plnkr.co/edit/siMNH53PCuvUBRLk6suc?p=preview by @brandonroberts

提交回复
热议问题