我正在使用
Angular 13
并创建了一个 myapp.mainrouting.js
文件并尝试声明 loadChildren
如下:
import {CustomerAppHomeComponent} from "../Home/CustomerApp.HomeComponent";
import {Routes} from "@angular/router";
export const MainRoutes: Routes = [
{ path: 'Home', component: CustomerAppHomeComponent },
{ path: 'Supplier', loadChildren: '../Supplier/CustomerApp.SupplierModule#CustomerAppSupplierModule' },
{ path: '', component: CustomerAppHomeComponent },
]
但是,我遇到以下错误:
error TS2322: Type 'string' is not assignable to type 'LoadChildrenCallback | undefined'.
8 { path: 'Supplier', loadChildren: '../Supplier/CustomerApp.SupplierModule#CustomerAppSupplierModule' },
~~~~~~~~~~~~
node_modules/@angular/router/router.d.ts:1998:5
1998 loadChildren?: LoadChildren;
~~~~~~~~~~~~
The expected type comes from property 'loadChildren' which is declared here on type 'Route'
对于动态导入你需要更新这个
{ path: 'Supplier', loadChildren: '../Supplier/CustomerApp.SupplierModule#CustomerAppSupplierModule' },
对此:
{
path: 'Supplier',
loadChildren: () => import('../Supplier/CustomerApp.SupplierModule').then(x => x.CustomerAppSupplierModule)
},
还要仔细检查您的 tsconfig.json 中是否有此行
"module": "esnext"
{
...
"compilerOptions": {
...
"module": "esnext"
...
}
}
你遇到这个问题是因为 angular 的新采用导致导入子模块的风格被弃用。
更改为这种格式
{ path: 'Supplier',
loadChildren: () => import('../Supplier/SupplierModule.module').then(m => m.SupplierModule },
// *supplier/...*is supposed to be your file name and the *m... us supposed to be your module name
~~~~~~~~~~~~
此外,请注意您的 tsconfig.json 文件可能需要修改,模块键,将其值更改为“esnext”。就是为了支持现在使用的动态模块加载
对于 Angular 13,下面的语法将起作用。喜欢使用承诺。 loadChildren 返回承诺。
{
path : 'product',
loadChildren: () => import("./product/product.module").then(module => module.ProductModule)
},