Angular 4 - Routes - How to create a separate module for managing routes and use it in app.module.ts file

前端 未结 2 1157
情深已故
情深已故 2021-01-14 18:21

I am newbie in Angular, I want to implement the routes in separate component and import the same component in app.module.ts file. How do I import t

相关标签:
2条回答
  • 2021-01-14 18:38

    you should create a separate module for routing and add your router info in this module.

    like this:

    routing.module.ts file structure

    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';
    
    import { LoginComponent } from './user/login/login.component'; //your component
    
    const routes: Routes = [
        { path: 'login', component: LoginComponent}
      ];
    
    @NgModule({
      imports: [ RouterModule.forRoot(routes) ],
      exports: [
          RouterModule
       ] 
    })
    export class RoutingModule { };
    

    import RouterModule and config your routs info then export your config (in export section of router module) for another module like app.module.

    then import and inject your routing module to your base module app.module

    like this:

    app.module.ts file structure

    import { RoutingModule } from './routing.module';
    
    @NgModule({
      declarations: [],
      imports: [
        RoutingModule
      ],
      exports: [],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
    
    0 讨论(0)
  • 2021-01-14 18:38

    AppRoutes is a class so you need to instanciate it before using it:

    let appRoutes = new AppRoutes(); 
    

    then

    ...
    RouterModule.forRoot(appRoutes.getRoutes()) 
    
    0 讨论(0)
提交回复
热议问题