Thursday, 10 January 2019

Angular 6 Services

Angular Services

Angular services concept always confuses newbies with server side REST services. If you are still not sure what it is, I will recommend you to read Angular documentation

Angular Services have responsibility to provide application data/business logic to components. Components should take/provide data to service and function as glue between view and service. It is service who can decide whether to provide mock data or go to server and fetch data from database/file/another service(s) etc.

Ideally, services should be feature oriented. You have choice to build a giant service class or micro services collections. In first approach, there shall be only one service which shall contain all business logic and shall be provided via Angular Dependency Injection in all components within system. Issue with this approach is, giant service class shall get bloated eventually leading performance issue. Every component shall get injected with service and functionality which is not required to consumer component at all. Do you think it is good?

In second approach (followed widely), feature specific micro service gets built. For example, if your system have Login, SignUp, Dashboard components then you shall build LoginService, SignUpService, DashboardService and so on. Each service shall contain functionality required for specific targeted component. Now this design looks good, isn’t it?


While building big and complex Single Page Application using Angular, you shall soon end up with hundreds and thousands of component classes. Having said so, you shall have similar number of Angular services injected. What is the problem here?

No matter how good naming convention you have followed for building components and services, there shall be time required to figure out specific name of service for specific class. Also you may end up writing duplicate service class with slightly different name for same component than other team built. If you are working in Extreme Programming model, your frontend developers are supposed to keep switching between modules/components/features. It should not take much time for them to figure out components and services associated.


We can solve this problem using Facade design pattern.

Facade Design Pattern

Facade discusses encapsulating a complex subsystem within a single interface object. This reduces the learning curve necessary to successfully leverage the subsystem. It also promotes decoupling the subsystem from its potentially many clients.

The Facade object should be a fairly simple advocate or facilitator. It should not become an all-knowing oracle or “god” object.

Here is the good read for Facade design pattern in details