【发布时间】:2018-08-15 14:40:43
【问题描述】:
我正在使用 VS 2017(框架 2.7)和 Angular 5 来开发我的应用程序。我想从 url 获取参数值。我在 app.module.ts 中写了以下内容:
RouterModule.forRoot([
{ path: '', component: HomeComponent, pathMatch: 'full' },
{ path: 'counter', component: CounterComponent },
{ path: 'fetch-data', component: FetchDataComponent },
{ path: 'create-strings', component: CreateStringsComponent },
{ path: 'strings/edit/:id', component: CreateStringsComponent },
{ path: 'fetch-strings/:prop', component: StringsComponent },
{ path: 'fetch-strings/:prop', component: StringsComponent },
{ path: 'fetch-strings/:prop', component: StringsComponent }
//{ path: '**', redirectTo: 'home' }
])
],
nav-menu.component.html菜单文件如下:
<li [routerLinkActive]='["link-active"]'>
<a [routerLink]="['/fetch-strings']" [queryParams]="{prop: 'loc'}" (click)='collapse()'>
<span class='glyphicon glyphicon-th-list'></span> Strings
</a>
</li>
<!--https://stackoverflow.com/questions/37880876/how-to-pass-query-parameters-with-a-routerlink-in-the-new-router-v-3-alpha-vlad-->
<li [routerLinkActive]='["link-active"]'>
<a [routerLink]="['/fetch-strings']" [queryParams]="{prop: 'dep'}" (click)='collapse()'>
<span class='glyphicon glyphicon-th-list'></span> Department
</a>
</li>
<li [routerLinkActive]='["link-active"]'>
<a [routerLink]="['/fetch-strings']" [queryParams]="{prop: 'des'}" (click)='collapse()'>
<span class='glyphicon glyphicon-th-list'></span> Designation
</a>
</li>
我想捕获参数值并相应地更改页面的和标题。为此,我在 Strings.Component.ts 文件中编写了以下代码:
constructor(public http: Http, private _router: Router, private _stringsService: StringsService, private _activeRoute: ActivatedRoute) {
this.getStrings();
}
//https://stackoverflow.com/questions/45309131/angular-2-4-how-to-get-route-parameters-in-app-component
ngOnInit() {
debugger;
//console.log(this._activeRoute.snapshot.params['prop']);
//this.var1 = this._activeRoute.snapshot.params['prop'];
//this.var2 = this._activeRoute.params.subscribe(params => { this.var1 = params['prop']; });
this._activeRoute.queryParams.subscribe((prop: Params) => {
console.log(prop);
});
if (this.var1 == "loc") {
this.title = "Location";
}
else if (this.var1 == "dep") {
this.title = "Department";
}
else if (this.var1 == "des") {
this.title = "Designation";
}
}
代码:
this._activeRoute.queryParams.subscribe((prop: Params) => {
console.log(prop);
});
正在正确显示参数值。 1)但是如何将参数值存储在变量中,以便我可以使用它来动态更改标题。
this.var1 = this._activeRoute.snapshot.params['prop'];
不工作。
2) 第二个问题,当我点击其他链接(nav-menu.component.html 文件)时,第一个菜单始终保持选中状态。
有什么线索吗?
谢谢
帕萨
【问题讨论】:
标签: asp.net angular angular-routing