【问题标题】:Angular 2 - Lifecycle hooks for lazy loaded modulesAngular 2 - 延迟加载模块的生命周期钩子
【发布时间】:2018-04-16 03:21:38
【问题描述】:

我正在使用延迟加载的 Angular 模块开发应用程序。

我有一个简单的问题:

是否可以在加载模块时捕获事件?

例如 OnInit。此链接解释了生命周期钩子,但仅适用于组件:Lifecycle hooks for components

我找不到任何解释如何挂钩模块的文档。

有人知道如何解决这个问题吗?

谢谢

【问题讨论】:

  • 我的问题 - 这是什么?问题应该有明确的问题陈述,最好是stackoverflow.com/help/mcve。模块没有钩子。组件可以。包括延迟加载的。
  • 一个更好的问题将涉及 context - 在模块生命周期的某个时刻,您尝试 做什么 是什么?否则就是XY problem
  • 感谢您的回复。我已经更新了我的问题。我的代码是一个简单的原型,用于显示在加载模块时是否可以捕获事件。因此,除此之外没有其他上下文。

标签: javascript angular module components lifecycle


【解决方案1】:

延迟加载模块的构造函数应该这样做

@NgModule({...})
export class MyLazyModule {
  constructor(/* service injection here if required */) {
    console.log('lazy module loaded');
  }
}

【讨论】:

  • 该死的。有点尴尬,我没有看到那个哈哈。它在我的解决方案中按预期工作。我有时会过度考虑角度的解决方案。不过感谢您的回答:)
  • 很高兴听到:)
【解决方案2】:

您可以使用两个路由器事件:RouteConfigLoadStartRouteConfigLoadEnd。您也可以使用LoadChildrenCallback。这些可能无法完全满足您的要求,但仍然会有所帮助。

您还可以使用以下技巧:

@NgModule({
    imports        : [BrowserModule, FormsModule, RouterModule, ROUTING],
    providers      : [
        {provide: CustomService, useClass: CustomService},
        ...
    ]
})
export class AppModule implements OnInit
{
    //force CustomService service creation or inject other app service,
    // so use can use it to fire event or do smth.
    constructor(handler:CustomService)
    {
        console.log('handler', handler);
        handler.fire('module created');
    }
}

【讨论】:

  • 感谢您的回复。我不明白您的回复(代码示例)。你的观点是模块可以挂钩像 OnInit 这样的生命周期事件吗?
  • 你没有钩子,但你可以检测模块实例何时创建并触发事件。
  • @kemsky,想知道什么时候会被解雇?在构建阶段?
猜你喜欢
  • 2017-02-22
  • 2017-11-13
  • 2017-05-16
  • 2017-01-18
  • 2018-11-18
  • 1970-01-01
  • 2017-11-22
  • 2017-03-29
相关资源
最近更新 更多