A detailed guide on Angular Services

What is Angular?

Angular is one type of framework that is used for building single-page client applications using HTML and Typescript. Having written in Typescript, Angular has features like Property binding, powerful views, intelligent code completion, etc. 

We have a situation where we need some code to be used everywhere on the page or in an angular application. Services help us to use shared components for data connection. Using services, we can access methods and properties in other components in the entire project.

Angular services are singleton objects which are instantiated only time during the lifetime of an application. It contains methods that are used to maintain data throughout the life of an application, i.e., every time data does not get refreshed and it is available in the application. Basically, in service, we have a well-defined class with the main purpose is to do something. In angular reusable service is designed to encapsulate data with different components and business logic.

The main purpose of using service is to organize and share business logic, models, or data and functions with different types of components of an entire Angular application.

Why Should We Use Services in Angular?

The main reason for Angular services came into existence is a separation of concerns. An Angular service is a stateless object it is used to provide some serviceable functions. For any component of Angular, like Controllers, Directives etc., for that these functions can be invoked. This helps in dividing the web application into small and different logical units which can be reused.

If you write all the business logic in components, you may face the following problems:

  • You will not be able to reuse that logic anywhere else in the application so you have to re-code the entire logic in the target component of your application.
  • Your components will become hard to maintain as you will have to maintain two copies of the same code in a single application.

So, if you want to wrap your business logic in a reusable Angular service, so you will not only make your components clean but also get the benefits of reusability and maintainability.

For example, your controller is responsible for the flow of data and also responsible for binding the model to view. An Angular application can have multiple controllers, which are used to fetch data that is required by the entire application. To make calls for similar data each controller will use a similar code. For that, we have to make an AJAX call to the server from the controller which is redundant. In this type of case, it is extremely useful to use a service, as we can write a service that contains the code to fetch data from the server and inject the service into the controller of our application. Services will have many functions to make a call from the controller. We can use these functions of services in the controller and make calls to the server, so using that way, we need not write the same code again in the application and it can be used in components other than controllers as well. Also, controllers no need to perform the task of fetching the data every time, because it works can be done by services, thus achieving the objective of Separation of Concerns.

Now, we create a service using following the command line command. The command for the creating service is:

 Following myservice is created in our app component

Following are the files created at the bottom of our application- myservice.service.specs.ts and myservice.service.ts.

myservice.service.ts

import { Injectable } from ‘@angular/core’;

@Injectable({

  providedIn: ‘root’

})

export class MyserviceService {

  constructor() { }

}

Here, the Injectable module is imported from the @angular/core. It contains the @Injectable method and a class called MyserviceService. Here, we will create our service function in this class. 

Dependency Injection

Dependency injection is used to provide components with the services they can use services into it. For defining a class as a service in Angular, the @Injectable() decorator is used. It provides the metadata. Metadata allows Angular to inject services into a component as a dependency. correspondingly, the @Injectable() decorator is used to indicate that a component or other class (such as another service, a pipe, or an NgModule) has a dependency with service.

Component Communication Using Angular Services

Reusable Angular services can also be used to establish communication between two or more components. The components may be as a parent-child relationship or maybe as a sibling. No matter which type of relation is between the components, the services can be used to share data between two components. We need public properties in the service class in which one component will set and the other component will be absorbing and also works in vice-versa. The service that is being used as a bridge between the two components must be injected into both the components.

Service Instances in Angular

In this, no matter how many components you try to consume a service in. As an Angular service by-default are singletons, it creates only one instance of the service. This will help services to establish communication between two or more components.

Providing services

For providing services You must register at least one provider of any service you are going to use. The provider may be own metadata of the service, making that service available everywhere, or you can register providers with specific modules or components. You register providers in the metadata of the service or in the @NgModule() or @Component() metadata.

  • The Angular CLI command ng generate service registers a provider with the root injector. for that your service by including provider metadata in the @Injectable() decorator. It is by default service registration. The example uses this method to register the provider of myservice class definition.

    @Injectable({

        providedIn: ‘root’

})

When you provide the service at the root level, Angular creates a single, shared instance of myservice and injects it into any class we want. Registering the provider in the @Injectable() metadata also allows Angular to optimize an app by removing the service from the compiled application if it isn’t used, a process known as tree-shaking.

  • When you register a provider with a specific NgModule, then the same instance of a service is available to all components in our NgModule. Following example shows how to register at this level. It uses the provider’s property of the @NgModule() decorator.

@NgModule({

      declarations: [

        AppComponent,

        MycomponentComponent

      ],

…}]

  • When you register a provider at the component level, then you get a new instance of the service with each new instance of that component. Now, how to register at the component level as shown in example. For that register a service provider in the providers property of the @Component() metadata.

src/app/myapp.component.ts (component providers)

@Component({

  selector: ‘app-root’,

  templateUrl: ‘./app.component.html’,

  providers:  [ myservice ]

})

Conclusion

In this blog, we have learned angular services and how to create services. We show what is the use of services. In short, using angular services we create it only one time and use it to inject a @Injectable method in any component of our entire project. So, using angular service, we can reuse components in our application.  

Author Bio: Ajay Patel – Technical Director, iFour Technolab Pvt. Ltd.

A Seasoned technocrat with years of experience building technical solutions for various industries using Microsoft technologies. With sharp understanding and technical acumen, have delivered hundreds of Web, Cloud, Desktop and Mobile solutions and is heading the technical department at iFour Technolab Pvt. Ltd.

Hire our Angular developers to address your business concerns using Angular technology.

By Anurag Rathod

Anurag Rathod is an Editor of Appclonescript.com, who is passionate for app-based startup solutions and on-demand business ideas. He believes in spreading tech trends. He is an avid reader and loves thinking out of the box to promote new technologies.