Javascript 在不知道完整路由的情况下按名称更改路由参数
在Angular 2中,是否可以获取当前URL,通过其配置的名称修改参数,然后导航到该参数 示例路线Javascript 在不知道完整路由的情况下按名称更改路由参数,javascript,html,angular,Javascript,Html,Angular,在Angular 2中,是否可以获取当前URL,通过其配置的名称修改参数,然后导航到该参数 示例路线 path: 'home' path: 'heroes/:universe' path: 'villains/:universe' 有效的URL包括: 现在,在根组件的某个地方,我想选择一些宇宙 // in App.component.ts universe: string; 我已经被困在第一步了。ActivatedRoute中似乎没有任何内容可以为我获取当前路由的路由配置
path: 'home'
path: 'heroes/:universe'
path: 'villains/:universe'
有效的URL包括:
// in App.component.ts
universe: string;
我已经被困在第一步了。
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]);
}
通过查看当前路线,你将如何判断它是英雄还是村人。这几乎奏效了。我必须使用激活路由的第一个子路由:
activatedRoute.firstChild.routeConfig.path
。我想这是因为我在根组件(AppComponent
)中编写了代码。很高兴能帮助您。我们可以根据您的调查结果更新答案,以帮助其他用户更快地找到类似问题的解决方案。
constructor(protected activatedRoute: ActivatedRoute) {
}
public loadData() {
var route = this.activatedRoute.routeConfig.path;
console.log(route);
}
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]);
}