Angular 2(二): 路由

前言

router是Angular 内置模块,可以使用cli 提供的指令来创建包含route 组件的项目

1
$ ng new router --routing

此时,在app.module.ts 文件中可以看到已经被自动引入到 imports组中。

1
2
3
4
imports: [
BrowserModule,
AppRoutingModule
],


路由组件相关字段含义

1. Routes,路由的配置项

  • 保存路由信息,即:url和component的对应关系
  • 指定组件展示在哪个路有插座上(<RouterOutLet></RouterOutLet>)

2. RouterOutLet,路由插座,即:激活的组件显示在Html 代码片段中的位置

3. Router,路由对象,提供在控制器中使用的一系列方法

  • navigate()
  • navigateByUrl()

4. RouterLink,在Html 中使用的导航指令

5. ActivatedRoute,当前激活的组件的路由对象

  • 路由地址
  • 路由参数

注意事项

1. 配置项中,path 对象的值不能使用”/“ 开头,这样可以使在项目中自由使用绝对路径和相对路径

1
2
3
4
5
6
const router:Router = [
{
path:"product", //path:"/product",错误写法
component:ProductComponet
}
];

应用

1
<a [RouterLink]="['/product']">GOTO</a>
  • 路由地址以’/‘ 开头,表示查找的是根目录组件
  • 值的形式是数组,由路由地址和参数组成:[‘url’,参数]

该写法等价于:

1
<a (click)="GOTO()">GOTO</a>

1
2
3
4
5
6
Controller:
constructor(private router:Router){}
GOTO():void{
this.router.navigate(['/product'])
}

2. 基础写法

  • 路由匹配是采取优先原则,通配符配置放在最后面,当路径错误是展现指定的页面
    1
    2
    3
    4
    5
    const router : Router =[
    { path:"",component:HomeComponent }
    { path:"product",component:Product }
    { path:"**",component:404Component } //通配符配置
    ]

3. 参数的传递和接收

路由参数传递的方式有三种,分别是:

① 在查询参数中传递
② 在路径中传递
③ 在配置项中使用特定对象data传递

  • 在查询参数中传递
    传递方式:

    1
    <a [routerLink]="['/product']" [queryParams]="{id:1}">GOTO</a>

    接收方式:

    1
    2
    3
    4
    5
    6
    7
    constructor(private routeInfo : ActivatedRoute){}
    private id : number;
    ngOnInit(){
    this.id = this.routeInfo.snapshot.queryParams["id"];
    }
  • 在路径中设置参数
    修改router中的配置:

    1
    { path:"product/:id", component:ProductComponent }

    修改Html中的RouterLink的写法:

    1
    <a [routerLink] = "['/product', 1]">GOTO</a>

    Controller:

    1
    this.id = this.routeInfo.snapshot.params["id"];
  • 在路由的配置项中使用data对象
    修改路由配置项:
    1
    2
    3
    4
    5
    6
    7
    8
    {
    path:"product",
    component:ProductComponent,
    data:[
    {id:1},
    {name:2},
    ]
    }

获取传进来的参数:

1
2
3
4
5
constructor(private routeInfo: ActivatedRoute ){}
ngOnInit(){
this.id = this.routeInfo.data[0]["id"];
}


参数快照和参数订阅

通过路由激活某一个组件之后,获取参数的方式有两种

  • 参数快照,关键字:snapshot

    1
    2
    3
    ngOnInit(){
    this.id = this.routeInfo.snapshot.params["id"];
    };
  • 参数订阅,关键字:subscribe

    1
    2
    3
    4
    5
    ngOnInit(){
    this.routeInfo.params.subscribe((params : Params) => {
    this.id = params["id"];
    })
    };

    参数订阅与参数快照的使用场景:
    当由HomeComponent进入到ProductComponent时,ProductComponent被激活,ngOnInit和constructor调用一次。
    例如:Product组件内部产品间的切换,由于id是通过参数在ngOnInit中获取的:
    ①如果使用snapshot的方式,组件未被销毁,noOnInit不再执行,那么显示在外部的id值将不再更新,出现数据错误;
    ②处理方式,采用subscribe的方式,当参数发生变化,即可更新信息;