Angular 2路由无法正常工作

时间:2016-09-04 02:18:12

标签: angular angular2-routing

我似乎无法在Angular 2中使用路由器与子项一起工作。该应用程序是我的第一个Angular 2应用程序,它非常简单,顶部有一个导航栏,应该填充下方的内容。页。每当我点击任何导航链接时,他们都导航到同一个孩子,甚至更糟糕的是那个孩子的内容堆叠,这意味着我点击一次,孩子加载到下面,我再次点击它再次加载下面,所以我有两次,等等。

完整内容可在此处找到:plunker

这是我的searching.routing.ts文件:

XCode

这是我的app.routing.ts文件:

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { AdvancedSearchComponent } from './advanced-search/advanced-search.component';
import { GuidedSearchComponent } from './guided-search/guided-search.component';
import { QuickSearchComponent } from './quick-search/quick-search.component';

const searchesRoutes: Routes = [
    {
        children: [
            { path: 'advanced-search', component: AdvancedSearchComponent },
            { path: 'guided-search', component: GuidedSearchComponent },
            { path: 'quick-search', component: QuickSearchComponent }
        ],
        path: '',
        component: GuidedSearchComponent
    }
];

export const searchesRouting: ModuleWithProviders = RouterModule.forChild(searchesRoutes);

所以再一次,这不能正常工作,但如果我在主文件中执行所有路由,就像这样:

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const searchesRoutes: Routes = [
    { path: 'searches', loadChildren: 'app/searches/searches.module#SearchesModule' },
    { path: '', redirectTo: "/searches", pathMatch: 'full' }
];

const appRoutes: Routes = [
    ...searchesRoutes
];

export const appRoutingProviders: any[] = [
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

但我想学习如何将搜索路由委托给子模块以使其更易于管理。

1 个答案:

答案 0 :(得分:5)

您应该在searchesRoutes内为您的子路径设置根组件,例如:

@Component({
    selector: 'art-search',
    template: `<router-outlet></router-outlet>`
})
export class SearchComponent {}

您还必须指定默认路线,如:

{ path: '', redirectTo: '/guided-search', pathMatch: 'full' }

然后您的 searching.routing.ts 文件将是:

const searchesRoutes: Routes = [
  {
    children: [
      { path: 'advanced-search', component: AdvancedSearchComponent },
      { path: 'guided-search', component: GuidedSearchComponent },
      { path: 'quick-search', component: QuickSearchComponent },
      { path: '', redirectTo: '/guided-search', pathMatch: 'full' }
    ],
    path: '', component: SearchComponent
  } 
];

在此处查看更多详情Plunker