我正在尝试在角度5中实现延迟加载。
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import {RouterModule , Routes} from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import {LocationStrategy, HashLocationStrategy} from
'@angular/common';
import { DataService } from './data.service';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from "./contact/contact.component";
import { NavComponent } from './nav/nav.component';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutComponent,
ContactComponent,
NavComponent
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule,
RouterModule.forRoot([
{path: 'home', component: HomeComponent},
{path: '', redirectTo: 'home', pathMatch: 'full'},
{path: 'about', component: AboutComponent},
{path: 'contact', component: ContactComponent},
])
],
providers: [DataService,{provide: LocationStrategy, useClass:
HashLocationStrategy}],
bootstrap: [AppComponent]
})
export class AppModule { }
我希望联系人和组件延迟加载。怎么做??我是否需要为此创建一些新的模块和组件?
答案 0 :(得分:1)
要实现延迟加载,请使用子路由,这些子路由是指延迟加载的Modules RoutingModule,在该模块中将进一步解析子路由: loadChildren:“ ./ pages / myPath / myPath.module#MyPathModule”
MaiModule-> MainRoutingModule-> childRoute = LazyLoadModule -> LazyLoadRoutingModule
const appRoutes: Routes = [
{
path: 'myPath',
loadChildren: './pages/myPath/myPath.module#LazyLoadedModule'
},
]
答案 1 :(得分:0)
您可以将AboutComponent和ContactComponent添加到名为“ LandingModule”的单独模块中。然后,您可以为着陆模块创建一个单独的路由页面。
const routes: Routes = [
{path: 'about', component: AboutComponent},
{path: 'contact', component: ContactComponent },
];
此后,您需要创建AppRoutingModule,其中包括用于创建延迟加载路由的应用程序级路由。
const routes: Routes = [
{
path: 'customers',
loadChildren: './landing/landing.module#LandingModule'
},
{
path: '', redirectTo: '', pathMatch: 'full'
}
];
如果您想了解更多信息,可以访问给定的链接。
除了将所有路由保留在appModule中之外,添加路由文件是一个好习惯。
答案 2 :(得分:0)
创建2个新模块:
ng generate module about --roputing
ng generate module contact --routing
为每个模块创建组件:
ng generate component about/components/about
ng generate component contact/components/contact
因为我们使用了-routing 选项,所以每个模块都将具有 about-routing.module.ts 和 contact-routing.module.ts 已创建。在这里,您需要指定模块的路由。将此添加到关于模块:
const routes: Routes = [
{ path: '', component: AboutComponent, pathMatch: 'full' }
];
对于联系人模块:
const routes: Routes = [
{ path: '', component: ContactComponent, pathMatch: 'full' }
];
将 app.module.ts 更改为:
RouterModule.forRoot([
{path: 'home', component: HomeComponent},
{path: '', redirectTo: 'home', pathMatch: 'full'},
path: 'about', loadChildren: './about/about.module#AboutModule' },
path: 'contact', loadChildren: './contact/contact.module#ContactModule' },
])
答案 3 :(得分:-1)
您必须使用指向主应用程序路由文件的子概念链接创建一个新模块,用于加载有关组件和相关组件。