Ionic5导入自定义服务报错does not have 'ɵmod' property怎么解决
报错原因
- Angular 中
@NgModule的imports数组仅支持导入NgModule模块类,不能直接导入服务、组件等非模块类型。你将MiscService服务错误写入了imports数组,Angular 会默认将它当作模块解析,找不到模块必备的ɵmod属性就会抛出对应报错。 - 若你的服务已经在
app.module.ts中完成全局注册,页面模块不需要重复导入/注册即可直接注入使用。
修复步骤
- 首先移除
HomePageModule中imports数组内的MiscService,修改后的模块配置如下:
@NgModule({ imports: [ CommonModule, FormsModule, IonicModule, HomePageRoutingModule, TranslateModule // 移除MiscService ], declarations: [HomePage], exports:[TranslateModule] }) export class HomePageModule { }
- 确认你的
MiscService本身配置了正确的可注入装饰器,默认使用官方命令生成的服务会自带全局注册配置,不需要在任何模块的providers数组重复注册:
@Injectable({ providedIn: 'root' // 全局注册标识 }) export class MiscService { // 服务逻辑代码 }
- 如果你不需要全局注册服务,仅想在当前页面模块范围内使用该服务,可以把
MiscService加入HomePageModule的providers数组,同时将服务的@Injectable配置改为providedIn: 'any'或者直接删除providedIn配置:
@NgModule({ imports: [ CommonModule, FormsModule, IonicModule, HomePageRoutingModule, TranslateModule ], declarations: [HomePage], exports:[TranslateModule], providers: [MiscService] // 服务添加到providers数组 }) export class HomePageModule { }
- 最后在页面组件的构造函数中注入服务即可正常调用:
export class HomePage { constructor(private miscService: MiscService) { // 直接调用服务方法即可 } }
内容的提问来源于stack exchange,提问作者Yokesh Varadhan
相关产品推荐
相关产品推荐

