文件AppRoutingModule
包含:
const routes: Routes = [
{
path: "events",
component: EventComponent,
children: [
{
path: 'add',
component: AddEventComponent
}
]
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
我尝试通过以下网址访问AddEventComponent
:localhost:4200/events/add
它没有打开,没有错误。
组件AddEventComponent
已在add-event.module.ts
中注册:
import { NgModule } from "@angular/core";
import { SharedModule } from 'src/app/SharedModule';
import { CompanyService } from 'src/app/api/CompanyService';
import { AddEventComponent } from './add-event-component';
@NgModule({
imports: [SharedModule],
declarations: [AddEventComponent],
exports: [AddEventComponent],
providers: [CompanyService]
})
export class AddEventModule { }
然后将AddEventModule
添加到主要AppModule
:
@NgModule({
declarations: [
],
imports: [
AddEventModule
]});
因此,我需要通过URL AddEventComponent
打开组件localhost:4200/events/add
,现在它总是打开父项EventComponent
AppModule :
@NgModule({
declarations: [
AppComponent,
NofoundComponent
],
imports: [
CommonModule,
BrowserModule,
HttpClientModule,
SharedModule,
LoginModule,
LanguageModule,
EventModule,
AddEventModule,
VisitorModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: CustomTranslateLoader,
deps: [HttpClient]
}
}),
SocketIoModule.forRoot(config),
AppRoutingModule
],
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: RequestInterception,
multi: true,
},
EventsService, VisitorsService, UserService, ExportService, AuthenticationGuard],
exports: [TranslateModule, AddEventModule],
bootstrap: [AppComponent]
})
export class AppModule { }
答案 0 :(得分:2)
在使用child routing时,向组件EventComponent
添加一个<router-outlet></router-outlet>
。呈现children
路由配置属性中定义的路由/组件是必需的。
EventComponent:
<!-- existing component content -->
<router-outlet></router-outlet>
这样,在children
中指定的任何组件都将在 EventComponent
内代替<router-outlet></router-outlet>
。
如果您未在路由配置中使用children
属性,则在<router-outlet></router-outlet>
中不需要其他EventComponent
:
const routes: Routes = [
{ path: "events", component: EventComponent },
{ path: "events/add", component: AddEventComponent }
];
但是,AddEventComponent
不会在内部 EventComponent
中呈现,而是代替 EventComponent
中的呈现。
希望有帮助!