[英]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.