Angular 2 - 如果用户尝试访问登录页面,则将用户重定向到主页。 (我需要它不要击中组件构造函数)

Angular 2 - Redirct a user to homepage if they try to access a logged in page. (I need it not to hit the components constructor)

Angular 2 - 如果用户尝试访问登录页面,则将用户重定向到主页。 (我需要它不要点击组件构造函数)

我正在使用 typescript 和 angular2。

目前只有在组件构造函数中没有调用服务时才有效。

目前我正在使用这样做(但它仍然会影响内部组件构造函数并导致错误):

import {Directive, Attribute, ElementRef, DynamicComponentLoader} from 'angular2/core';
import {Router, RouterOutlet, ComponentInstruction} from 'angular2/router';

@Directive({
  selector: 'router-outlet'
})
export class LoggedInRouterOutlet extends RouterOutlet {
  publicRoutes: any;
  private parentRouter: Router;

  constructor(_elementRef: ElementRef, _loader: DynamicComponentLoader, _parentRouter: Router, @Attribute('name') nameAttr: string) {
    super(_elementRef, _loader, _parentRouter, nameAttr);
    this.parentRouter = _parentRouter;
    this.publicRoutes = { 
      '/Home': true 
    };
  }

  activate(instruction: ComponentInstruction) {     
      console.log("here");
      this.parentRouter.navigate(['/Home']);
      return super.activate(instruction); 
  }
}

它目前仅在内部页面的构造函数中没有任何内容时才有效。

你需要的是受保护组件前面的@CanActivate 指令。

https://angular.io/docs/ts/latest/api/router/CanActivate-decorator.html

@CanActivate(() => checkAuth())
export class ProtectedCMP {}

考虑这个 Plunker (protected.component.ts )

https://plnkr.co/edit/sGzQIFsLJaFHsjGT1MpP?p=preview