也许所有其他答案都是针对 Angular 2.X 的。
现在它不适用于 Angular 5.X。
我正在处理它。
仅使用 NavigationEnd,您无法获取之前的 url。
因为路由器从“NavigationStart”、“RoutesRecognized”、...到“NavigationEnd”工作。
您可以检查
router.events.forEach((event) => {
console.log(event);
});
但即使使用“NavigationStart”,您仍然无法获取以前的网址。
现在您需要成对使用。
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/pairwise';
constructor(private router: Router) {
this.router.events
.filter(e => e instanceof RoutesRecognized)
.pairwise()
.subscribe((event: any[]) => {
console.log(event[0].urlAfterRedirects);
});
}
通过pairwise,你可以看到url 的来源和目的地。
“RoutesRecognized”是从源 URL 到目标 URL 的变化步骤。
所以过滤它并从中获取以前的网址。
最后但并非最不重要的,
将此代码放在父组件或更高版本中(例如,app.component.ts)
因为此代码在完成路由后触发。
更新角度 6+
The events.filter
给出错误,因为过滤器不是事件的一部分,因此将代码更改为
import { filter, pairwise } from 'rxjs/operators';
this.router.events
.pipe(filter((evt: any) => evt instanceof RoutesRecognized), pairwise())
.subscribe((events: RoutesRecognized[]) => {
console.log('previous url', events[0].urlAfterRedirects);
console.log('current url', events[1].urlAfterRedirects);
});