Should i use multiple services file in angular 5 or just 1 file for all the functions?

It all depends on you'r strategy, you should see the future and think about all the possibilities. Here is my logic in my apps.

generally I use one specific service for each module for example if we want to have a website for a university we have

  1. Student.module
  2. Class.module

Which each module have components and one service and for each service we will have four general actions which are

  1. Add
  2. Edit
  3. Delete
  4. List

So I will have Services in the following addresses.

  1. App/class/class.service.ts
  2. App/student/student.service.ts

The other logic is to create a folder called service in the app-root and place all the services in it. ( which is not recommended ) which is structured as below

  1. app/service/class.service.ts
  2. app/service/student.service.ts

The worst logic is to create one file known as service.ts in the app-root and paste all the service codes in it ( never recommend at all )


For deciding the architecture of Angular for service files, you need to keep below points in mind:

  • Module (feature) specific files should be kept in separate module. Your code should have high cohesion
  • If there are common service files that are required by different modules, then create a shared module and put all common.svc.ts files in it. Reason being, you can reuse the service for all the modules.
  • While creating service files in shared module, try to break it down further depending on the the features which they provide. This will break your long service files into meaningful small files which are easier to maintain.
  • You can also create one common.svc file which itself doesn't have any business logic, rather it provides access of all the common services. The importance of this common.svc will be that you won't have to inject all the shared services inside components. You can have access of all shared service by just injecting this common.svc file. It'll act as a gateway to access all the shared services. So now you can have access of, let's say 5 shared services by just injecting 1 common.svc inside a component.

Do let me know if you need more clarification for any of the above points.

You can refer SOLID design principal to have a better code irrespective of your language

Tags:

Angular