RouterModule
添加路由器指令和服务提供商。
Adds router directives and providers.
class RouterModule {
static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders<RouterModule>
static forChild(routes: Routes): ModuleWithProviders<RouterModule>
}
参见
Routing and Navigation for an overview of how the router service should be used.
路由与导航 以获得如何使用路由器服务的概览。
说明
在构建应用时,管理状态的转换是最难的任务之一。对 Web 来说尤其如此,你还要确保这个状态同时在 URL 中反映出来。 另外,我们通常会希望把应用拆分成多个发布包,并按需加载。要让这些工作透明化,可没那么简单。
Managing state transitions is one of the hardest parts of building applications. This is especially true on the web, where you also need to ensure that the state is reflected in the URL. In addition, we often want to split applications into multiple bundles and load them on demand. Doing this transparently is not trivial.
Angular 的路由器解决了这些问题。使用路由器,你可以声明式的指定应用的状态、管理状态的转换,还可以处理好 URL,还可以按需加载发布包。
The Angular router service solves these problems. Using the router, you can declaratively specify application states, manage state transitions while taking care of the URL, and load bundles on demand.
静态方法
Creates and configures a module with all the router providers and directives. Optionally sets up an application listener to perform an initial navigation. | ||||||
参数
返回值
|
创建一个具有所有路由器指令和一个用于注册路由的提供商。 Creates a module with all the router directives and a provider registering routes. |
指令
名称 | 说明 |
---|---|
| 让你可以在应用中链接到特定的路由。 Lets you link to specific routes in your app. |
| 当此链接指向的路由激活时,往宿主元素上添加一个 CSS 类。 Lets you add a CSS class to an element when the link's route becomes active. |
| 允许你在应用中链接到特定的路由。 Lets you link to specific routes in your app. |
| 一个占位符,Angular 会根据当前的路由器状态动态填充它。 Acts as a placeholder that Angular dynamically fills based on the current router state. |
使用说明
RouterModule 可能会被多次导入:每个惰性加载的发布包都会导入一次。 但由于路由器要和全局共享的资源 - location 打交道,所以不能同时激活一个以上的 Router
服务。
RouterModule can be imported multiple times: once per lazily-loaded bundle. Since the router deals with a global shared resource--location, we cannot have more than one router service active.
这就是需要两种方式来创建本模块的原因:RouterModule.forRoot
和 RouterModule.forChild
。
That is why there are two ways to create the module: RouterModule.forRoot
and RouterModule.forChild
.
forRoot
创建一个包含所有指令、指定的路由和Router
服务本身的模块。forRoot
creates a module that contains all the directives, the given routes, and the router service itself.forChild
会创建一个包含所有指令、指定的路由,但不含Router
服务的模块。forChild
creates a module that contains all the directives and the given routes, but does not include the router service.
当注册在根模块时,该模块应该这样用:
When registered at the root, the module should be used as follows
@NgModule({
imports: [RouterModule.forRoot(ROUTES)]
})
class MyNgModule {}
对于子模块和惰性加载的子模块,该模块应该这样用:
For submodules and lazy loaded submodules the module should be used as follows:
@NgModule({
imports: [RouterModule.forChild(ROUTES)]
})
class MyNgModule {}