Ionic Angular 12. ApplicationRef的循环依赖关系

qxgroojn  于 2023-01-28  发布在  Ionic
关注(0)|答案(1)|浏览(155)

我得到Error: NG0200: Circular dependency in DI detected for ApplicationRef.,以防:

import { ModalController } from '@ionic/angular';
import { MyModalComponent } from 'MyModalComponentPath';

@Injectable({
    providedIn: 'root'
})
export class MyCoreService {
    constructor(
        private modalController: ModalController
    ) { }
    
    private async openModal(): Promise<void> {
        const modal = await this.modalController.create({
            component: MyModalComponent
        });

        modal.present();
    }
}

我也有类似的核心服务使用ModalController没有这个错误。
循环依赖在这里是怎么可能的?有人遇到过这个问题吗?
完整错误消息:

Error: NG0200: Circular dependency in DI detected for ApplicationRef. Find more at https://angular.io/errors/NG0200
    at throwCyclicDependencyError (core.js:216)
    at R3Injector.hydrate (core.js:11433)
    at R3Injector.get (core.js:11256)
    at injectInjectorOnly (core.js:4751)
    at Module.ɵɵinject (core.js:4755)
    at Object.AngularDelegate_Factory [as factory] (ionic-angular.js:2320)
    at R3Injector.hydrate (core.js:11437)
    at R3Injector.get (core.js:11256)
    at injectInjectorOnly (core.js:4751)
    at Module.ɵɵinject (core.js:4755)
vuv7lop3

vuv7lop31#

我得到了和你完全一样的错误。在做了一些测试之后,我发现只有当你把ModalController注入到一个Serviceconstructor中,而这个Service又被当前活动的Component使用时,这个错误才会发生。
我不知道是什么原因造成的,但是一个解决方法是使用Injector示例将ModalController延迟加载到Service中,这将阻止抛出循环依赖错误。
下面是一些代码来说明这一点:

import { ModalController } from '@ionic/angular';
    import { Injector } from '@angular/core';
    
    
    @Injectable({
      providedIn: 'root'
    })
    export class MyService {
    
      constructor(private injector:Injector){}

      async presentModalDialog(params: any) {
        const modal = await this.injector.get(ModalController).create({  //The lazy loading is done with the get method of Injector
          component: ModalDialogComponent,
          componentProps: params,
        });
        return await modal.present();
      }
    
    }

或者,您也可以使用Injector示例只加载ModalController一次,然后将该示例赋给ModalController类型的类变量。

相关问题