I have multiple API's for different components, so what should I prefer to do, whether putting all the functions in one service or should I create multiple services. Example-component 1 uses 4 particular functions out of 10 total functions. should I create 1 service for 10 functions or two different services consists of 4 and 6 functions respectively
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
Which each module have components and one service and for each service we will have four general actions which are
So I will have Services in the following addresses.
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
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:
common.svc.ts
files in it. Reason being, you can reuse the service for all the modules.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.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
Refer this : Angular Style Guide by Angular.io
You should follow SOLID principles , and for your case follow Single Responsibility principle
you class should targeted to do single function i.e. single responsiblity , which says that you should not mix all your code i.e. resposiblity in one class
Example : customer class handle customer related activity it should not handle user related activity
If you are adding all method which are not related then you are putting too many responsibility to one class. To avoid that you should separate responsibility by creating classes which have related methods only in it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With