首页 > 解决方案 > 为什么我们不能在 Ionic 中进行循环依赖?

问题描述

在 Ionic 我做了 2 项服务来提供数据

export class DocumentService {

  constructor(favorisService: FavorisService) { }

  async GetById(id: number): Promise<DocumentModel>{
    let path = this.favorisService.getPath();
    // Get document's additionnal datas from BDD
    // Gets back document depending on path
  }

  async GetById(id: number): Promise<DocumentModel>{
     //request server and sends back a document
  }
}

export class FavorisService {

  constructor(httpServer: httpServerService) { }

  async Synchronize(id: number): Promise<FavorisModel>{
     //if favoris was never synchronized, get document on server
     //then downloads document with document.getDocument
  }

  GetPathToDocument(){//returns favoris's document's path}
}

我不明白为什么我不能在documentService和documentService中导入收藏服务,服务的目的是提供数据,为什么他们不能互相提供数据?

我做了第三个服务,叫做 FavorisDocumentService

export class FavorisDocumentService{

  constructor(
    httpServer: httpServerService, favorisService: FavorisService,
    documentService: DocumentService
  ) { }

  async GetById(id: number): Promise<FavorisModel>{
    this.favoris = await this.favorisService.getById(id);
    this.favoris.document = await this.documentService.getById(id);
  }
}

问题不是它不起作用(实际上它起作用),问题是我必须为每个组合或对象创建另一个服务。我这样做是因为我的项目较小,而且我只有 2 个关系迫使我创建第三个服务,但现在我必须制作“DocumentFavorisUserServices”和其他...(在我的示例中,您可以说我只是将 documentService 放入偏好服务,但有时我需要 documentService 中的偏好服务)

不允许做“循环依赖”的目的是什么,正确的方法是什么?(我使用 Ionic 4)

编辑 - -

一个收藏夹可以包含一个文档,但是一个文档并不总是链接到一个收藏夹,并且这个文档,取决于收藏夹,可以存放在不同的地方,这取决于收藏夹如何管理它。所以“路径”数据在收藏夹中而不是在文档中。这就是为什么有时我需要在文档中使用收藏夹,因为当我有我的“getdocument”(我把它放在文档服务中)时,我需要该文档的路径(将它取回)。在这种情况下,单一责任原则有点模糊哪个对象具有哪个责任(我对我的对象示例进行了编辑)

标签: angularionic-frameworkcircular-dependency

解决方案


我认为你没有以正确的方式去做。AFavorisService应该只获得'favoris',而aDocumentService应该只忙于处理文件。这些对象彼此具有密钥,不应该改变这一点。如果您需要来自组件中两者的数据,则应该从这两个服务中查询。如果您倾向于经常使用这种模式,那么您可以创建一个包装服务来为您执行此操作(就像您所做的那样)

尽量让您的服务只承担一项责任和/或重组您的数据对象结构,使其没有循环引用。

Ionic 中不允许循环依赖的原因是因为 ES5 中不允许这样做。

你在代码中引用的越多,测试就越难,理解也就越复杂——你最终会得到意大利面条式的代码。此外,许多引用创建循环依赖关系,直接导致错误。

在 ES6 中,这已经解决了,但我相信你永远不应该有循环依赖(参见上面的引用)。


推荐阅读