微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

仅针对服务检测到 Angular 11 循环依赖

如何解决仅针对服务检测到 Angular 11 循环依赖

我有两个 Angular 服务,分别是 WindowDetailsServiceSessionHelperService。现在,在我的 WindowDetailsService 代码中,我需要有以下场景:

WindowDetailsS​​ervice:

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;
    }
}

我得到的错误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

我无法从 SessionHelperService 中取出 Window-details 的代码,因为它不仅包含 Cordova 窗口类型的代码,还包含 Web 和 Electron 的代码

现在我的问题是我无法从 SessionHelperService 中取出与 WindowDetailsS​​ervice 相关的代码,反之亦然。由于这是一个大 项目,如果我对此进行更改,它将影响项目中的许多其他相关文件。请建议我该怎么做

解决方法

尝试使用 Injector 服务以这种方式获取 SessionHelperService

WindowDetailsS​​ervice:

  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);
  }
,

另一种方法是创建例如 x 服务文件并导入您的 SessionHelperService 和 WindowDetailsS​​ervice,这样您的所有服务都可以正常工作而不会出现循环依赖错误

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。