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
- Student.module
- Class.module
Which each module have components and one service and for each service we will have four general actions which are
- Add
- Edit
- Delete
- List
So I will have Services in the following addresses.
- App/class/class.service.ts
- 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
- app/service/class.service.ts
- 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 thiscommon.svc
will be that you won't have to inject all theshared
services insidecomponents
. You can have access of allshared
service by just injecting thiscommon.svc
file. It'll act as a gateway to access all theshared
services. So now you can have access of, let's say 5shared
services by just injecting 1common.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