如何组织 API 调用和其他功能的最佳做法是什么?

What are the best practices for how to organize API calls and other functions?

这是一个更笼统的问题,但我有一个服务 DocumentCorrespondenceService,其端点如下:

constructor(private http: HttpClient, private route: Router) { }


getDossierEntry(patientUUID: string,   type: String = '' ): Observable<DossierEntry[]> {
  const entryType = type === '' ? 'all' : 'type/' + type;
  return this.http.get<DossierEntry[]>(`${this.baseUrl}/${patientUUID}/DossierEntry/` + entryType);
}

getDossierEntryFileData(patientUUID: string, entryID: number ): Observable<HttpResponse<Blob>> {
  return this.http.get('https://dev-engine.mijnhep.nl/api/patient/${patientUUID}/DossierEntry/' + entryID + '/fileData', {
    responseType: 'blob',
    observe: 'response'
  });

并且我有一个具有功能的组件。但是这些功能会被其他组件触发。

 gotoItem(index, type: string) {
    this.showingSingle = true;

    switch (type) {
      case 'correspondence': {
        this.single = this.correspondenceEntries[index];
        break;
      }
      case 'attachments': {
        this.single = this.attachmentEntries[index];
        break;
      }
      default: {
        break;
      }
    }
    this.showingSingle = true;
  }

  goBack() {
    this.showingSingle = false;
  }

我的问题是:通常的做法是什么?

重命名:DocumentCorrespondenceService 为

DocumentCorrespondenceApiService 

和其他服务:

DocumentCorrespondenceService  

里面的功能。并在使用该功能的组件中注入:

DocumentCorrespondenceService  

所以你有两个服务:

一个用于 api 调用,另一个用于函数。

谢谢

有很多事情要考虑。关于您对具有 100 个端点的服务的评论,您可能会想要将它分成一点。这里有一个 link 直接指向样式指南,它提供了有关如何组织代码和塑造项目的建议。

https://angular.io/guide/styleguide#rule-of-one

使用指南形成您自己的意见,了解哪些对您的项目有效,哪些无效。另外,不要为了创建文件而创建文件,如果您的 API 调用和处理对这些调用的响应的函数可以存在于同一服务中,那么就这样做。如果维护代码变得很麻烦并且文件变得太大,那么将它拆分成易于管理的东西。