【发布时间】:2019-11-18 13:00:13
【问题描述】:
在 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”(我把它放在文档服务中)时,我需要该文档的路径(将其取回)。在这种情况下,单一职责原则有点模糊哪个对象具有哪个职责(我对我的对象示例进行了编辑)
【问题讨论】:
-
其实我不明白我为什么要“创建”任何东西,提供者总是一样的,如果你在某个地方编辑它,它会保留数据,当你提供它时,你已经提供了一个现有对象
-
是的,这将是一个 Angular 问题,而不是具体的离子问题。并且回复:您的问题:当一个模块中的小局部更改传播到其他模块并产生不需要的全局影响(程序错误,编译错误)时,循环依赖可能会导致多米诺骨牌效应。循环依赖也可能导致无限递归或其他意外失败。
-
@AmaniteLaurine Angular 需要创建您的服务实例。所以它必须调用它们的构造函数,并传递它们需要的参数。所以它需要创建一个 FavorisService,并传递给它一个 DocumentService。所以它需要创建一个 DocumentService,并传递一个 FavorisService。
标签: angular ionic-framework circular-dependency