您可以通过内置的ActivatedRoute 服务来实现这一点,正如他们在documentation 中所说的那样,您的“路线信息一站式商店”。
首先,您需要在组件的构造函数中注入服务。假设你有一个 Todo 组件和一个 Birthday 组件,无论哪种情况,构造函数都应该是这样的:
constructor(private currentRoute: ActivatedRoute, private router: Router) { }
然后,在您的 ngOnInit() 函数中,您需要订阅您的 ActivatedRoute 实例的 url 属性,这是一个 Observable:
ngOnInit() {
this.currentRoute.url
.subscribe(routeParts => {
this.periodArray = [];
for (let i = 1; i < routeParts.length; i++) {
this.periodArray.push(routeParts[i].path);
}
});
}
组件路由作为 Observable 提供的原因是,在组件的生命周期中,它可以接收多个不同的路由。就像你的情况一样“/todo/2017”或“todo/2017/01”等。你的组件只会被创建一次,ngOnInit()也只会被调用一次,但是通过订阅ActivatedRoute.url observable,你将始终收到有关当前路线的通知。
上面的代码块用激活路由中除了第一个 url 部分之外的所有部分填充了一个数组,它为您提供了除了初始“/todo”或“/birthday”段之外的所有传递参数。
现在您可以通过在此参数数组的开头添加所需的路径来导航到另一个组件,例如:
navigateBirthdays() {
this.periodArray.unshift('/birthday');
this.router.navigate(this.periodArray);
}
这是 Todo 组件的完整代码及其模板:
todo.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
templateUrl: './todo.component.html',
})
export class TodoComponent implements OnInit {
periodArray = [];
constructor(private currentRoute: ActivatedRoute, private router: Router) { }
ngOnInit() {
this.currentRoute.url
.subscribe(routeParts => {
this.periodArray = [];
for (let i = 1; i < routeParts.length; i++) {
this.periodArray.push(routeParts[i].path);
}
});
}
navigateBirthdays() {
this.periodArray.unshift('/birthday');
this.router.navigate(this.periodArray);
}
}
todo.component.html
<p>
List of Todo items for {{periodArray.join("-")}}
</p>
<button (click)="navigateBirthdays()">Show Birthday items</button>
生日组件看起来几乎相同。以上允许您在“/todo/2017/1/3”和“/birthday/2017/1/3”之间以及“/todo/2017”和“/birthday/2017”等之间来回切换 -无需设置任何特定的路由规则。
附注:对于可选参数,通常最好不要将它们包含在 URL 路径中,而是将它们作为可选路由对象提供 - 请参阅文档的 this section。