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 }

转载于:https://www.cnblogs.com/cyei/p/10794595.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值