2017-01-05 6 views
1

パスの最初の要素としてルートパラメータを使用する可能性はありますか? たとえば、のは言わせて、我々は、天候や都市のポータルを持っているが、当社の「コンテキスト」(「コンテキスト」せずに任意のページにアクセスする可能性がない)であるので、我々のようなページを持つようにしたい:パスの最初の要素としてパスパラメータを設定

/:city/dashboard 
/:city/airhealth 

どのようにそのようなパスをルートに追加しますか?私はこのような何かを持っている可能性がある知っている:

/dashboard/:city 
/airhealth/:city 

が、すべてのページは、市内のコンテキストを持っている必要がありますときに最初の例では、この場合は、より適しています。

答えて

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(); 
    } 

} 

ここでは、作業中です。https://plnkr.co/edit/Purfk2msPE1XcZgjowvd?p=preview

関連する問題