为什么路由器打破angular2生命周期挂钩? [英] Why the router break the lifecycle hooks in angular2?

查看:230
本文介绍了为什么路由器打破angular2生命周期挂钩?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在TS有该模板的应用程序:

I have an application in ts which have this template :

<main>
    <test></test>
    <router-outlet></router-outlet>
</main>

有了这个RouteConfig

With this RouteConfig

@RouteConfig([
    { path: '/myApp/game', name: 'GamePage', component: GameComponent, useAsDefault: true}
])

下面是游戏组件:

import {Component} from 'angular2/core';

@Component({
    selector: 'test',
    template: '<div>{{title}}</div>'
})
export class GameComponent {
    title = "myTest";

    constructor(){
        console.log("I am constructed")
    }

    ngOnInit(){
        console.log("initGameComponent");
    }
}

因此​​,这组件被导入两次(一次由指令测试,由路由器出口的第二时间),这是我想以显示该问题

So this component is imported twice (once by the directive 'test', a second time by the router outlet), which is what I want in order to show the problem.

我的问题是第一次(当我不使用路由器)一切都工作正常,但第二次,{{title}}的'未呈现和控制台不登录initGameComponent但不要登录我在建造。

My problem is that the first time (when I don't use the router) everything's works fine, but the second time, the '{{title}}' is not rendered and the console don't log 'initGameComponent' but DO log 'I am constructed'.

问题是为什么?! (如果它是对不起愚蠢的东西,因为我开始与angular2,但我真的无法弄清楚)

The question is why ?! (Sorry if it's something stupid because I'm starting with angular2, but I really can't figure it out)

推荐答案

工作Plunker -with没有问题,因为你所描述 搜索结果
boot.ts

import {Component,bind} from 'angular2/core';
import {Router,ROUTER_PROVIDERS,RouteConfig, ROUTER_DIRECTIVES,APP_BASE_HREF,LocationStrategy,RouteParams,ROUTER_BINDINGS} from 'angular2/router';
import {bootstrap}        from 'angular2/platform/browser';

import{GameComponent} from 'src/GameComponent';

@Component({
  selector: 'my-app',
    template: `
    <h1>Component Router</h1>
    <hr> 
    <test></test>
    <hr>
    <router-outlet></router-outlet>
   `,
  directives: [ROUTER_DIRECTIVES,GameComponent]
})
@RouteConfig([
  //{path:'/ComponentOne', name: 'ComponentOne', component: ComponentOne, useAsDefault:true},

   { path: '/myApp/game', name: 'GamePage', component: GameComponent, useAsDefault: true}

])
export class AppComponent {

}

bootstrap(AppComponent, [
      ROUTER_PROVIDERS,bind(APP_BASE_HREF).toValue(location.pathname)
]);

GameComponent.ts

 import {Component,View} from 'angular2/core';

 @Component({
   selector:'test',
    template: `
    <div>{{title}}</div>

    `
  })

  export class GameComponent {
    title = "myTest";

    constructor(){
        console.log("I am constructed")
    }

    ngOnInit(){
        console.log("initGameComponent");
    }
  }

这篇关于为什么路由器打破angular2生命周期挂钩?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆