[英]Routing between Modules in Angular
我正在构建简单的角度应用程序。 有学生和老师两个模块。 这是我的项目的组织方式。
首先,当用户进入应用程序时,我让他选择他是老师还是学生。
根据用户将被重定向到相应模块的内容。
import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import { StudentModule } from './student/student.module';
import { TeacherModule } from './teacher/teacher.module';
import { HomeComponent } from './home/home.component';
const routes: Routes = [
{
path: '',
component: HomeComponent
},
{
path: 'student',
loadChildren: () => StudentModule
},
{
path: 'teacher',
loadChildren: () => TeacherModule
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
这是我的app.routing.ts
文件。
当我重定向到我想在这些模块中的组件之间路由的模块时,我的问题是我们。 我应该在每个模块中添加另一个<router-outlet>
还是可以使用AppModule
唯一的<router-outlet>
来AppModule
。
如果我应该添加另一个<router-outlet>
我应该如何为这些模块编写我的路由器类。
Angular v8、v9 及更高版本的延迟加载方式
https://angular.io/guide/lazy-loading-ngmodules
// In app module route
{
path: 'your-path',
loadChildren: () => import('./path-to/your.module').then(m => m.YourModule)
}
// in your module
const yourRoutes: Routes = [
{ path: '', component: YourComponent }
];
export const yourRouting = RouterModule.forChild(yourRoutes);
@NgModule({
imports: [
yourRouting
],
declarations: [
YourComponent
]
})
export class YourModule{
}
Angular v7、v6 及以下的延迟加载方式
// In app module route
{
path: 'your-path',
loadChildren: 'app/your.module#YourModule'
}
// in your module
const yourRoutes: Routes = [
{ path: '', component: YourComponent }
];
export const yourRouting = RouterModule.forChild(yourRoutes);
@NgModule({
imports: [
yourRouting
],
declarations: [
YourComponent
]
})
export class YourModule{
}
不是懒加载方式
只需在主模块中导入YourModule
,如果路由没有延迟加载,它就会工作。
@NgModule({
imports: [
BrowserModule,
FormsModule,
YourModule,
routing
],
declarations: [
AppComponent
],
providers: [
appRoutingProviders
],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
花一些时间阅读路由文档https://angular.io/guide/router
是的,您需要为各个模块定义路由,并在您需要提供的模块组件文件中
下面应该是文件结构
- Teacher
-teacher.component.html --> here you should put <router-outlet>
-techer-routing.module.ts --> here you need to define routes for teacher module
-teacher.module.ts --> import techer-routing.module here
-Logincomponent
-login.component.html
-login.component.ts
-Homecomponent
-home.component.html
-home.component.ts
与学生的另一个模块相同。
下一步是指定教师模块内部路由。 以下是可能的内容
教师路由.module.ts
以下是教师模块的示例路线
const routes: Routes = [
{path: '', component: TeacherComponent, children: [
{path: '', component: TeacherComponent,data: {title: "Teachers"}},
{path: 'Home', component:HomeComponent, data: {title: "Home"}},
{path: 'Register', component:RegisterComponent, data: {title:
"Register"}},
]
}
]
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class TeacherRoutingModule{}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.