Как мне устранить предупреждение “Обнаружена циклическая зависимость” в Angular?

#angular #typescript

#angular #typescript

Вопрос:

У меня есть предупреждение о циклической зависимости между компонентом и сервисом. Это мой модальный компонент.

 import { ModalService } from './modal.service';

@Component({
  selector: 'modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ModalComponent implements OnInit, OnChanges {

  constructor(private modalService: ModalService { }

  close() {
    this.modalService.close();
  }

}
 

Это сервис:

 import { ModalComponent } from './modal.component';

 @Injectable({
   providedIn: 'root'
 })
 export class ModalService {

 dialogComponentRef: ComponentRef<ModalComponent>;


  constructor(  private appRef: ApplicationRef,
            private cfResolver: ComponentFactoryResolver,
            private injector: Injector) { }



  open(title, content) {
   const contentComponentFactory = this.cfResolver.resolveComponentFactory(content);
   const modalComponentFactory = this.cfResolver.resolveComponentFactory(ModalComponent);

   const contentComponent = contentComponentFactory.create(this.injector);
   const modalComponent = modalComponentFactory.create(this.injector, [[contentComponent.location.nativeElement]]);

   if (title) {
     modalComponent.instance.title = title;
   }

   modalComponent.instance.active = true;

   this.dialogComponentRef = modalComponent;

   document.body.appendChild(modalComponent.location.nativeElement);

   this.appRef.attachView(contentComponent.hostView);
   this.appRef.attachView(modalComponent.hostView);
 }


 close() {
   this.appRef.detachView(this.dialogComponentRef.hostView);
 } 
}
 

Мне нужно импортировать ModalComponent в службу, потому что я должен использовать его в качестве параметра в resolveComponentFactory. В этой службе я создаю функцию open, которую можно будет использовать в других компонентах для открытия модального;

Я также создаю функцию закрытия в службе, которую мне нужно вызвать внутри модального компонента, когда я нажму на какую-нибудь кнопку, например «закрыть»; и это причина, по которой мне нужен ModalService внутри моего ModalComponent.

Я не могу найти решение. Как я могу исправить это предупреждение?