简体   繁体   中英

Angular 11 Circular Dependency detected for services only

I have two Angular services say WindowDetailsService and SessionHelperService . Now, in my code for WindowDetailsService I have I need to have the below scenario:

WindowDetailsService:

import { SessionHelperService } from '../pkg/session/session-helper.service';

constructor(private sessionHelperService: SessionHelperService) {
}

getCurrentSession() {
    const session = this.sessionHelperService.get(true);
}

SessionHelperService

import { WindowDetailsService } from '../pkg/session/window-details.service';

constructor(private windowDetailsService: WindowDetailsService) {
}

windowOperations(windowType: String) {
    Switch(windowType) {
        case 'Cordova':
            if (shouldCloseWindow) {
                this.windowDetailsService.setReadyToClose(true);
                if (closeSession) {
                    this.closeUserSession(closeSession)
                        .finally(this.windowDetailsService.closeCurrentWindow);
                } else {
                    this.windowDetailsService.closeAllWindows();
                }
            }
            break;
        case 'Web':
            break;
        case 'Electron':
            break;
    }
}

The error that I get is Warning: Circular dependency detected: session-helper.service.ts -> window.details.ts -> session-helper.service.ts

Warning: Circular dependency detected: window-details.service.ts -> session-helper.service.ts -> window-details.service.ts

I can not take out the code of Window-details from SessionHelperService as it consists the code not only for Cordova window type but also for Web and Electron.

Now my problem is that I can not take out the code related to WindowDetailsService from SessionHelperService and vice versa. Since this is a big project and if I make change to this, it will impact whole lot of other dependent files in the project. Please suggest as to what should I do

Try to use the Injector service to get the SessionHelperService this way:

WindowDetailsService:

  import { Injector } from '@angular/core';
  
  @Injectable({
    providedIn: 'root'
  })
  export class ...

  private sessionHelperService: SessionHelperService

  /**
   * Constructor
   */
  constructor(private injector:Injector) {
  }

  getCurrentSession() {
    this.sessionHelperService = injector.get(SessionHelperService));
    const session = this.sessionHelperService.get(true);
  }

another way is create for example x service file and import your SessionHelperService and WindowDetailsService in that, in this way all your services do their job without circular dependency error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM