2015-12-04 11 views
8

私がしたいのは、Angular2で設定されたルートのリストを反復してナビゲーションを動的に構築することです。私は設定されたルートにアクセスすることができるルータ内のどこにも見当たりません。誰もこれを試したことがありますか?Angular2には、ルータからルートリストを取得する方法がありますか?

Routerregistryのプロパティを調べましたが、使用できるものはありません。

@Component({ 
    selector: 'my-app' 
}) 
@View({ 
    directives: [ROUTER_DIRECTIVES, CORE_DIRECTIVES], 
    template: ` 
     <h1>Routing Example</h1> 
     <div> 
      <div> 
       <b>Main menu: </b> 
       <a [router-link]="['Home']">Home</a> | 
       <a [router-link]="['One']">One</a> | 
       <a [router-link]="['Two']">Two</a> 

       <!-- 
        // I would rather do something like this: 
        <a *ng-for="#route of router.routes" [router-link]="['route.name']">{{ route.name }}</a> 
       --> 

      </div> 
      <div> 
       <router-outlet></router-outlet> 
      </div> 
     </div> 
    ` 
}) 
@RouteConfig([ 
    { path: '/', redirectTo: '/home' }, 
    { path: '/home', as: 'Home', component: Main }, 
    { path: '/one', as: 'One', component: One }, 
    { path: '/two', as: 'Two', component: Two }, 
]) 
export class MyApp { 
    constructor(public location: Location, public router: Router){ 
    } 
} 

答えて

4

また、リンクを動的に生成する必要もありました。私が理解しているように、問題は、ルータにリンクを生成する方法がなく、手作業でそれらを入れないことです。[router-link]。しかし... but they plan to add them。ルータのキューにlot of featuresがありますので、すぐに追加してください(

今のところ私はこの作業を行いました。私はこのコンポーネントでルーターの設定を使用することができます。 :

let routeConfig = [ 
    { path: '/', name: 'Intro', component: IntroRouteComponent, useAsDefault: true }, 
    ... 
    { path: '/projects', name: 'Projects', component: ProjectsRouteComponent }, 
    { path: '/about', name: 'About', component: AboutRouteComponent }, 
]; 

@Component({ 
    directives: [ROUTER_DIRECTIVES], 
    providers: [], 
    selector: 'app', 
    template: ` 
    <a (click)="back()" *ngIf="prevRoute">{{ prevRoute }}</a> 
    <a (click)="forward()" *ngIf="nextRoute">{{ nextRoute }}</a> 
    `, 
}) 
@RouteConfig(routeConfig) 
export class AppComponent { 
    private nextRoute: any; 
    private prevRoute: any; 

    constructor(private _router: Router) { 
    this._router.subscribe(route => { 
     let i = routeConfig.findIndex(r => r.path === ('/' + route)); 
     this.prevRoute = routeConfig[i - 1] ? routeConfig[i - 1].name : false; 
     this.nextRoute = routeConfig[i + 1] ? routeConfig[i + 1].name : false; 
    }); 
    } 

    back() { 
    this._router.navigate(Array(this.prevRoute)); 
    } 
    forward(): any { 
    this._router.navigate(Array(this.nextRoute)); 
    } 

} 
関連する問題