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

别等时光非礼了梦想. 提交于 2019-12-01 07:28:03

问题


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 the routes component in app.module.ts file.

I was trying like:
app.routes.ts

import { UsersComponent } from './users/users.component';

export class AppRoutes {
    getRoutes() {
        return [
            {
                path: 'users',
                component: UsersComponent
            }
        ];
    }
}

in app.modules.ts

import { AppRoutes } from './app.routes';
@NgModule({
  declarations: [
    AppComponent,
    UsersComponent,
  ],
  imports: [
    BrowserModule,
    HttpModule,
    HttpClientModule,
    RouterModule.forRoot(AppRoutes.getRoutes())
  ],
  providers: [UsersService],
  bootstrap: [AppComponent]
})
export class AppModule { }

I am getting error in here:

RouterModule.forRoot(AppRoutes.getRoutes())

回答1:


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 {}



回答2:


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

let appRoutes = new AppRoutes(); 

then

...
RouterModule.forRoot(appRoutes.getRoutes()) 


来源:https://stackoverflow.com/questions/48402318/angular-4-routes-how-to-create-a-separate-module-for-managing-routes-and-use

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!