首页 文章

Angular @NgModule初始化中导入和导出的目的

提问于
浏览
0

我正在经历Angular Tour Of Heroes tutorial,我刚到路由器部分 . 我很困惑为什么他们这样做:

app-routing.module.ts文件:

@NgModule({
    //Exporting the routermodule allows router directives available to AppModule components
    //This initialized the routermodule with routes so available through
    exports : [RouterModule],
    imports : [RouterModule.forRoot(routes)]
})

出口真的有什么作用?我注意到如果我没有创建这个模块并在“app.module.ts”文件中完成所有操作,我需要做的就是将RouterModule.forRoot(routes)添加到导入 . 我甚至不需要导入RouterModule .

我不明白的是 app.module.ts 是否要导入 app-routing.module.ts 文件导入 RouterModule.forRoot(routes) ,为什么模块仍然需要导出 RouterModule ?不应该 RouterModule.forRoot(routes) 提供指令吗?

对不起,这可能会令人困惑,但我无法理解出口的重要性 .

1 回答

  • 1

    这里有很多事情,我同意将你的思想包裹起来可能是一个挑战 . The imports array is how you register dependencies with a module and the exports array is how you declare those dependencies as public making their services, directives, components, etc available for use in other modules.

    既然你提到了RouterModule,我将以此为例 . app.module.ts is the root of your application and any module registered at the root will be made available to the entire application . 大多数应用程序都需要路由,因此您的应用程序需要RouterModule . 要在根模块中保持代码清洁,常见的模式是将路由逻辑合并到app-routing-module.ts中 .

    为了使用Angular提供的所有路由服务/指令,您必须将RouterModule导入app-routing.module.ts . 通过导入RouterModule,您可以使用它的指令在app-routing.module.ts中定义路由 . 现在,您只需要应用程序中的一个路由器服务实例 . 为了实现这一点,您在导入RouterModule时调用了forRoot()方法 . forRoot()方法是由Angular Build 的用于创建单例的约定,在这种情况下,它创建了路由器服务的单例(这是一个完全不同的主题,稍后将查看) .

    请记住,您希望在根模块(app.module.ts)中导入app-routing.module.ts,以在应用程序的根目录中注册路由 . 除此之外,您仍然希望能够在应用程序的其余部分中使用路由来导航 . 为了实现这一点,你在app-routing.module.ts中将RouterModule声明为导出,从而当你在应用程序的根目录中注册app-routing.module.ts时,使其所有的指令和服务可供其他应用程序使用 . (app.moudle.ts)

    这是一个复杂的主题,关于这个问题有很多好文章 . 为了得到更详细的解释,我建议从这篇文章开始:

    In depth article on modules

相关问题