Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript Angular 2-如果用户试图访问登录页面,请将其重新连接到主页。(我需要它,以免击中组件构造函数)_Typescript_Angular_Angular2 Routing - Fatal编程技术网

Typescript Angular 2-如果用户试图访问登录页面,请将其重新连接到主页。(我需要它,以免击中组件构造函数)

Typescript Angular 2-如果用户试图访问登录页面,请将其重新连接到主页。(我需要它,以免击中组件构造函数),typescript,angular,angular2-routing,Typescript,Angular,Angular2 Routing,Angular 2-如果用户试图访问登录页面,请将其重新连接到主页。(我需要它,以免击中组件构造函数) 我用的是打字脚本和angular2 当前仅当我在组件构造函数中没有调用服务时才起作用 目前我正在使用它来执行此操作(但它仍然会命中内部组件构造函数并导致错误): import {Directive, Attribute, ElementRef, DynamicComponentLoader} from 'angular2/core'; import {Router, RouterOutlet,

Angular 2-如果用户试图访问登录页面,请将其重新连接到主页。(我需要它,以免击中组件构造函数)

我用的是打字脚本和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指令

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


this.parentRouter.navigate(['/Home'])false)例如,它不会重定向,您必须为此编写额外的代码。我得到一个名为:Declaration expect的错误。是否需要导入CanActivate?@AngularM对于构造函数,我的建议是尽量不使用构造函数,而是使用
ngOnInit
和/或
routerOnActivate
方法来设置初始状态。在使用构造函数时有一些注意事项,这可能会在将来影响您。
@CanActivate(() => checkAuth())
export class ProtectedCMP {}