2016-09-17 42 views
11

最新角2.0.0,並通過最新的角CLI 1.0.0-beta.14,節點:6.6.0,操作系統:Linux的x64

我做什麼:

1)創建新項目無提供RouterOutletMap

ng new angular-test 
ng g component projects 
ng g component typings 

2)添加簡單的路由

/src/app/app.component.html

<router-outlet></router-outlet> 

/src/app/app.module.ts

export const ROUTES: Routes = [ 
    { 
    path: '', 
    redirectTo: '/projects', 
    pathMatch: 'full' 
    }, 
    { 
    path: 'projects', 
    component: ProjectsComponent, 
    }, 
    { 
    path: '/typings', 
    component: TypingsComponent 
    }, 
    { 
    path: '**', redirectTo: '' 
    } 
]; 

@NgModule({ 
    declarations: [ 
    AppComponent, 
    ProjectsComponent, 
    TypingsComponent 
    ], 
    imports: [ 
    BrowserModule, 
    FormsModule, 
    HttpModule, 
    RouterModule.forChild(ROUTES) 
    ], 
    providers: [], 
    bootstrap: [AppComponent] 
}) 
export class AppModule { } 

我得到什麼:

EXCEPTION: Error in ./AppComponent class AppComponent - inline template:3:0 caused by: No provider for RouterOutletMap! 
ORIGINAL EXCEPTION: No provider for RouterOutletMap! 

enter image description here

如何我試圖解決這個問題

我試圖添加在AppModule中,RouterOutletMap提供程序,異常不會拋出,但應用程序不會重定向到項目並且不顯示嵌套組件

回答

25

您需要爲應用程序模塊調用RouterModule.forRoot,而不是forChild。前者adds all the core providers,而the latter doesn't。您應該爲子模塊使用forChild,而不是應用程序模塊。

+0

嗨我遇到了同樣的問題,我使用'.forRoot'。在這裏注意看看? http://stackoverflow.com/questions/42321705/how-to-fix-error-in-app-app-component-html151-caused-by-no-provider-for-rout –

0

我也有這個問題和。這是我如何避免這一點.....有些時候這將有所幫助。 祝福!

路由陣列 - app.routes.ts

const appRoutes:Routes =[ 
{ 
    path: 'home', 
    component: CarouselComponent 
}, 
{ 
    path: 'profile', 
    component:UserDashboardComponentComponent, 
    children: [ 
    { 
     path: 'overview', 
     component: ProfileOverviewComponent 
    }, 
    { 
     path: 'post', 
     component: PostAddComponent 
    } 
    ] 
    } 
]; 

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

app.module.ts

@NgModule({ 
declarations: [ 
    AppComponent, 
    CarouselComponent, 
    ....... 
], 
imports: [ 
    BrowserModule, 
    MdTabsModule, 
    MaterialModule, 
    MdInputModule, 
    BrowserAnimationsModule, 
    FormsModule, 
    HttpModule, 
    WebRouting 
], 
providers: [], 
bootstrap: [AppComponent], 
}) 

export class AppModule { } 

tempale.html

<li> 
    <a [routerLink]="['/profile/overview']" routerLinkActive="active" > 
     Overview 
    </a> 
    </li> 
    <li> 
    <a [routerLink]="['/profile/post']"routerLinkActive="active"> 
     PostAdd 
    </a> 
    </li>