是否有可能将路由参数作为路径的第一个元素? 例如,假设我们有天气门户,城市是我们的'上下文'(没有'上下文'就无法访问任何页面),所以我们希望有这样的页面:
/:city/dashboard
/:city/airhealth
如何在路线中添加此类路径?我知道有可能有这样的事情:
/dashboard/:city
/airhealth/:city
但是当所有页面都必须有城市背景时,第一个例子在这种情况下更合适。
答案 0 :(得分:0)
我认为这样做不会有任何问题。您只需要修改路由文件和路由链接。
这是代码
<强> app.routing.ts 强>
import { Routes, RouterModule } from '@angular/router';
import ComponentOne from './component-one';
import ComponentTwo from './component-two';
export const routes: Routes = [
{ path: '', redirectTo: 'component-one', pathMatch: 'full' },
{ path: 'component-one', component: ComponentOne },
{ path: ':id/dashboard', component: ComponentTwo }
];
export const appRoutingProviders: any[] = [
];
export const routing = RouterModule.forRoot(routes);
<强> app.component.ts 强>
import {Component} from '@angular/core';
@Component({
selector: 'app',
template: `
<nav>
<a [routerLink]="['/component-one']">Component One</a>
<a [routerLink]="[123,'dashboard']">Component Two (id: 123)</a> <-- replace 123 with city name
</nav>
<div style="color: green; margin-top: 1rem;">Outlet:</div>
<div style="border: 2px solid green; padding: 1rem;">
<router-outlet></router-outlet>
</div>
`
})
export class AppComponent {
}
<强>组件two.ts 强>
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'component-two',
template: 'Component Two with route param <b><code>ID: {{ id }}</code></b>'
})
export default class ComponentTwo {
private id;
constructor(private route: ActivatedRoute) {}
private ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.id = +params['id']; // use (+) converts string 'id' to a number other wise use params['id'] directly
});
}
private ngOnDestroy() {
this.sub.unsubscribe();
}
}
这是工作的plnkr https://plnkr.co/edit/Purfk2msPE1XcZgjowvd?p=preview