在Angular 2中,是否可以获取当前URL,通过其配置名称修改参数,然后导航到它?
示例路由
path: 'home'
path: 'heroes/:universe'
path: 'villains/:universe'
有效的URL包括:
- https://example.com/home
- https://example.com/heroes/marvel
- https://example.com/heroes/capcom
- https://example.com/villains/marvel
- https://example.com/villains/capcom
现在我想选择宇宙的根组件中的某个地方。
// in App.component.ts
universe: string;
<!-- in App.component.html -->
<select [(ngModel)]="universe" (ngModelChange)="navigateToUniverse($event)">
<option value="marvel">Marvel</option>
<option value="capcom">Capcom</option>
</select>
示例
- 当前路线是
/heroes/marvel
,我选择CAPCOM->导航到/heroes/capcom
- 当前路线是
/villains/marvel
,我选择CAPCOM->导航到/villains/capcom
在我的脑海中,我想应该这样做:
// in App.component.ts
navigateToUniverse(universe: string): void {
/*
* 1. get the route config of the current ActivatedRoute
* eg. /heroes/:universe
* -or- /villains/:universe
* (or /home)
* 2. replace the :universe parameter with the selected value
* 3. call Router.navigate with the new URL
* /
}
我已经陷入了第一步。ActivatedRoute
中似乎没有任何东西可以为我提供当前路由的路由配置。
您可以从activatedRoute
属性获取此信息
constructor(protected activatedRoute: ActivatedRoute) {
}
public loadData() {
var route = this.activatedRoute.routeConfig.path;
console.log(route);
}
它将记录您当前的路由模板。在我的示例中,"users/:id"
。请检查。
首先从 @angular/router
导入路由器import { Router } from '@angular/router';
constructor(private _router: Router){}
navigateToUniverse(universe: string): void {
// Use Router to get the current Url.
let currentUrl = this._router.url;
currentUrl = currentUrl.replace(currentUrl .substring(r.lastIndexOf('/')),'')
// 2. replace the :universe parameter with the selected value
let newUrl = currentUrl + '/' + universe;
// 3. call Router.navigate with the new URL
this._router.navigate([newUrl]);
}