環(huán)境
node 10.15.0
ionic 4.12.0
cordova 9.0
# platforms
cordova-android:8.0.0
cordova-ios: 5.0.0
加載過程
相關(guān)文件
.
├── app-routing.module.ts # 路由
├── app.component.html # 頁面
├── app.component.spec.ts # 測試
├── app.component.ts # 代碼
├── app.module.ts # module
index.html
main.ts
第一步
index.html
引入AppComponent
<app-root></app-root>
main.ts
加載AppModule
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
第二步
app.component.html
引入ion-router-outlet,用于加載其他頁面
<ion-app>
<ion-router-outlet></ion-router-outlet>
</ion-app>
第三步
app-routing.module.ts
路由配置
此處定義了默認(rèn)路由(懶加載方式)
值得一提的是:ionic在創(chuàng)建pages時,會自動在app.routing中添加路由配置。
const routes: Routes = [
{path: '', redirectTo: '/index', pathMatch: 'full'},
{path: 'index', loadChildren: './pages/index/index.module#IndexPageModule'}
];
app配置(app.module)
首先看一下代碼
@NgModule({
// 聲明AppComponent
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
// 聲明ngx-logger配置(可忽略)
LoggerModule.forRoot({
level: NgxLoggerLevel.DEBUG,
serverLogLevel: NgxLoggerLevel.DEBUG
}),
// IonicModule:其中包含ionic的組件等
IonicModule.forRoot(),
// IonicStorage(插件)
IonicStorageModule.forRoot(),
// 路由
AppRoutingModule,
// 網(wǎng)絡(luò)請求
HttpClientModule
],
// 提供的服務(wù) (插件部分必須在此引入)
providers: [
StatusBar,
SplashScreen,
Camera,
ImagePicker,
FileTransfer,
WebView,
{provide: ErrorHandler, useClass: GlobalErrorHandler},
{provide: RouteReuseStrategy, useClass: IonicRouteStrategy},
{provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true}
],
bootstrap: [AppComponent]
})
# 可先忽略
export class AppModule {
static injector: Injector;
constructor(private injector: Injector) {
AppModule.injector = injector;
}
}
路由配置(app-routing)
const routes: Routes = [
{path: '', redirectTo: '/index', pathMatch: 'full'},
{path: 'index', loadChildren: './pages/index/index.module#IndexPageModule'}
];
@NgModule({
providers: [SelectivePreLoading],
imports: [
RouterModule.forRoot(routes, {preloadingStrategy: SelectivePreLoading, useHash: true})
],
exports: [RouterModule]
})
export class AppRoutingModule {
}
RouterModule.forRoot(routes, {preloadingStrategy: SelectivePreLoading, useHash: true})
查看定義,具體支持哪些配置
ExtraOptions
export interface ExtraOptions {
// 路由追蹤 用于調(diào)試
enableTracing?: boolean;
// hash方式路由(如:#/index)
useHash?: boolean;
initialNavigation?: InitialNavigation;
errorHandler?: ErrorHandler;
// 預(yù)加載路由策略
preloadingStrategy?: any;
onSameUrlNavigation?: 'reload' | 'ignore';
scrollPositionRestoration?: 'disabled' | 'enabled' | 'top';
anchorScrolling?: 'disabled' | 'enabled';
scrollOffset?: [number, number] | (() => [number, number]);
paramsInheritanceStrategy?: 'emptyOnly' | 'always';
malformedUriErrorHandler?: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree;
relativeLinkResolution?: 'legacy' | 'corrected';
}
此處配置了路由預(yù)加載策略。
什么事路由預(yù)加載?
場景:
在A頁面,點(diǎn)擊按鈕跳轉(zhuǎn)B頁面,此時如果我們在A頁面就預(yù)先將B頁面加載,即可提升一定的用戶體驗(yàn)。
下一篇將詳細(xì)介紹路由預(yù)加載策略。