使用angular声明周期方法,避免在constructor进行太多的工作,只需在constructor中创建和声明变量即可
在ngModel的import中导入我们的router,RouterModule.forRoot()
路径可以是相对和绝对路径,“:id”这样的表示代表route参数id。data属性是与指定router关联的参数数据,对活动的router可见,空路径是默认路径,router采用先匹配取胜原则
RouterLink directive可以用作箭头指向router导向,使用RouterLinkActive 添加或删除css,router-outlet标签用来显示相应
router的component,它的router由RouterLink指定
Router State每个ActivatedRoute都会被标记到router tree
router使用步骤:
- 导入router库
- 设置
<base href>
,例如app为根目录 - 创建一个router module(保持Routing Module 和应用它的module在同一文件夹下),在router
module的NgModule里import添加RouterModule.forRoot,再将RouterModule export导出
在相应位置添加导航routerLink and routerLinkActive指示符 - 在相应位置使用router-outlet指定显示组件
- 用RouterModule.forRoot配置router module
注:The RouterModule.forRoot should only be provided for the AppModule. Since we are in a feature module, we’ll use RouterModule.forChild method to only register additional routes.
ActivatedRoute能够获取route中包含的所有信息,包括url和参数等
The Routes are an array of route definitions
It’s standard practice for feature modules with routing components to define their own routes.
Never call RouterModule.forRoot in a feature routing module,which is intended for the app root module only.Always call RouterModule.forChild in a feature routing module.
app-routing.module.ts范例