Angular(Ionic)服务和模型依赖关系



有人告诉我,对于Ionic项目,我必须为每个对象使用一个服务。

我的型号:

export class Document{
idDocument: number;
listFields: Fields[];
}
export class Field{
idParentDocument: number;
idLinkToOtherDocument: Document;
}

我的服务:

export class DocumentService{
constructor(private http: httpService, private fieldService: FieldService){}
getFields(document: Document){
this.fieldService.getFieldsByDocumentId(document.id);
//gets the fields of the document
}
getDocument(id: number){
//gets the document and its fields
}
}
export class FieldsService{
constructor(private http: httpService, private documentService: DocumentService){}
getParentDocument(field: Field){
//gets the parent document of the field
}
getLinkedDocument(field: Field){
//gets the linked document of the field
}
getFieldsByDocumentId(id: number){
//gets the fields by document Id
}
}

有时我需要从其他对象访问对象,就像在我的例子中一样,但正如你所想象的,这最终会导致循环依赖。我不知道我应该做什么,以java为例,你只需要调用函数,但在angular中你不能。我可以回到我以前的设计模式,所有的功能都在对象中,而不是在服务中,我必须传递所有其他服务(数据库服务、服务器服务…(,但这将是一个巨大的重构,因为我被告知设计不好(我发现使用objectServices更好,我可以访问所有服务,而无需将它们作为参数传递(

我该怎么办?

就我个人而言,我既不会将服务作为参数传递,也不会将它们相互注入。重构它们将比以后重构它们或尝试维护此代码或修复错误花费更少。让我们把它分解一下:

getFields(document: Document){ // you only need a documentId not entire document object
this.fieldService.getFieldsByDocumentId(document.id); 
} 
//as the name say it return fields uses fields service you shouldn't have to redeclare it in document service.
// If someone wants to get fields of document he/she should use fields service ! 

export class FieldsService{
constructor(private http: httpService, private documentService: DocumentService){}
getParentDocument(field: Field){
// returns document and it should belong to DocumentsService.
// probably you will make an api call here do you need entire field object? NO
}
getLinkedDocument(field: Field){
// same as above
}
getFieldsByDocumentId(id: number){
// its ok.
}
}

如果您的对象在您的应用程序中存在。比方说,当你不需要API调用来获取文档的字段时,我建议你使用像NgRx这样的东西,它可以帮助你保持应用程序的状态集中。

最新更新