Getting Angular2 error 'No provider for Router! (RouterOutlet -> Router)'

后端 未结 6 800
你的背包
你的背包 2020-12-09 08:07

I use Angular2 alpha39 and Babel to transpile the ES6 JS file. I\'m not using typescript.

I created a component which displays correctly. I added a

6条回答
  •  情歌与酒
    2020-12-09 08:57

    Answer on Dec 23rd 2016 (Angular v2.4.1, Router v3.4.1 - should work for any NG v2.x.x + Router v3.x.x)

    I just migrated three of our apps from the Webpack Starter Seed to Angular CLI (v1.0.0-beta.24) and hit this issue.

    Only a tiny fraction of what's on the NG 2 massive router doc page is required:

    An app-routing.module.ts file (typically in src/app/ folder) looking like this sample:

    import { NgModule }              from '@angular/core';
    import { RouterModule, Routes }  from '@angular/router';
    
    const appRoutes: Routes = [
      { path: '', component: YourHomePageComponent },
      { path: 'next-page',   component: NextComponent }
    ];
    
    @NgModule({
      imports: [
        RouterModule.forRoot(appRoutes)
      ],
      exports: [
        RouterModule
      ]
    })
    export class AppRoutingModule {}
    

    Import AppRoutingModule into your main module (typically src/app/app.module.ts):

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        AppRoutingModule  // <--- The import you need to add
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    Ensure you have somewhere in your main html (often src/app/app.component.html) as this is where router content is injected.

提交回复
热议问题