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

最后都变了- 提交于 2019-12-01 10:41:37
Hasan Fathi

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

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

let appRoutes = new AppRoutes(); 

then

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