Router的使用

使用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使用步骤:

  1. 导入router库
  2. 设置<base href>,例如app为根目录
  3. 创建一个router module(保持Routing Module 和应用它的module在同一文件夹下),在router 
    module的NgModule里import添加RouterModule.forRoot,再将RouterModule export导出 
    在相应位置添加导航routerLink and routerLinkActive指示符
  4. 在相应位置使用router-outlet指定显示组件
  5. 用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范例

import { NgModule }             from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

export const routes: Routes = [
  { path: '', redirectTo: 'contact', pathMatch: 'full'},
  { path: 'crisis', loadChildren: 'app/crisis/crisis.module#CrisisModule' },
  { path: 'heroes', loadChildren: 'app/hero/hero.module#HeroModule' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值