【问题标题】:ngOnInit life cycle hook behaviour with routing module?ngOnInit 生命周期钩子行为与路由模块?
【发布时间】:2017-02-01 23:16:26
【问题描述】:

我在应用的根路由模块中使用以下路由:

const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'home',
        component: HomeDetailsComponent,
      },
      {
        path: 'home',
        component: HomeDetailsComponent,
        children: [
          {
            path: 'room/:id', 
            component: RoomDetailsComponent,
          },
        ]
      },
      {
        path: 'sectorNumber',
        component: SectorNumberComponent
      },
      {
        path: '**',
        redirectTo: 'home',
      },
    ]
  }
];

现在,在 HomeDetailsComponent 内部,我使用 OnInit 生命周期挂钩来调用 http get 方法,并在此基础上进行一些事件处理。但是,我注意到通过这种路由,我的 HomeDetailsComponent 被初始化了两次。一次当我导航到'http://localhost:3000/#/curriculum/' 时,第二次当我导航到'http://localhost:3000/#/curriculum/chapter/1' 路线时。谁能告诉我为什么会这样?

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:

    因为组件不会被不同的路由重用。您导航离开的路线中的组件将被销毁,而您导航到的组件将被创建。仅当 from-route 和 to-route 相同但参数值 (:id) 发生更改时才不同。

    【讨论】:

    • 如果from-route和to-route相同但是参数值(:id)改变了就不会重新初始化,是这个意思吗?
    • 完全正确。 . . .
    • 因为我尝试了同样的方法,并且在这种情况下它也在重新初始化。我正在从 'xxx/home' 到 'xxx/home/2' 并且可以看到它正在重新初始化。
    • 但那是两条不同的路线,一条不带参数,一条带参数。你必须配置两条路由,才能做到这一点。
    猜你喜欢
    • 2015-12-08
    • 2017-03-07
    • 2021-06-14
    • 1970-01-01
    • 2019-08-13
    • 2020-01-15
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多