3-2 路由_路由对象详解
1. Router
app-routing.moudle.ts中配置 Routes
1 const routes: Routes = [ 2 {path: '', component: HomeComponent}, 3 {path: 'product', component: ProductComponent} 4 ];
注意:
1. path中,不能用 / 开头。
2. Routes中放的是路有对象,路由对象可以有多个,每一个路由对象至少包含两个属性,
一个属性为path 即路由的路径,一个属性为路由下级的组件。
2. RouterOutlet占位符
RouterOutlet占位符存放在模块的组件模板中,声明路由配置中配置的组件模板将要放在什么位置
1 <router-outlet></router-outlet>
3. RouterLink 链接
一般在a标签中作为一个属性用,起到点击后链接页面的左右
1 <a [routerLink]="['/']">主页</a> 2 <a [routerLink]="['/product']">商品详情</a>
注意:
1. 此时里面的路径必须使用带 / 的,表示使用根路由。
2. 使用RouterLink时注意,参数是一个数组,数组中可以带有其他信息
3. Routes + RouterOutlet + RouterLink :可以组成一个跳转回路,完成所需的跳转。
4. Router 控制器
在主模板中:添加按钮和点击方式:
1 <input type="button" value="商品详情input" (click)="toProductDetails()">
在控制器中,编写方法,方法中存放路由地址
1 export class AppComponent { 2 title = 'router'; 3 constructor(private router: Router) { 4 } 5 toProductDetails() { 6 this.router.navigate(['/product']); 7 } 8 }
其中:
构造器中可以获取到路由
点击事件中使用路由的navigate()方法可以传入地址参数。
Routes + RouterOutlet + Router(控制器中) :可以组成一个跳转
5. ActivatedRoute
ActivatedRoute 获取激活路由对象中携带的参数
1、构造器获取ActivatedRoute激活路由对象
1 constructor(private routeInfo: ActivatedRoute) { }
2、初始化数据时获取参数中的数据
1 ngOnInit() { 2 this.productId = this.routeInfo.snapshot.queryParams['id'];//从参数中获取id 3 this.productId = this.routeInfo.snapshot.params['id']; //从url中获取id 4 }