How to use an Anagular 8 Service?


In Angular, services are singleton objects which normally get instantiated only once for the entire angular application. Every service contains several methods and that includes some functionality to do. It is a mechanism to share functionality or responsibility within one or more than components.

We know, using angular we can create nested-based components. Once our applications are nested, we may need to use the same functionality. Instead of writing same code in multiple components. We can write one place and we can share data with different components. The best way to use service to handle this.

In first versions of angular, we used to create services using providers, factories, delegates, values, etc. and also it is clear to which one need to use. But, in angular 8 it makes it clear to create services by two following ways.

  • Creating service with @Injector decorator

  • Register the class with provider or inject the class by using dependency injection.

Let’s look below, how to define a service in our application.

We can create our own services based on the requirement. To create a service, follow this steps.

  • First create one service.ts file with the proper name.

  • In this file, import Injectable from @angular/core package and provide @Injectable decorators at the beginning of the class.

  • Export the class object. So that we can this service in other components.

  • Write business logic based on the requirement inside export class object.

Note

When we our own service with provider metadata, we need to import in appp.module.ts file to utilize that service functionalities. If we didn’t import created service it is not visible to the whole application. If we import created service only one component without importing into main module, then that service only available to that particular component. If we provide the service in main module, for entire application only instance will be created for the service.

Let’s look into code below.

Example

Create a service class in app folder. I created getMessageService.service.ts file in app folder.

Add code like given below in getMessageService.service.ts file.

import { Injectable } from '@angular/core'; @Injectable() export class GetMessageService { constructor() { } showMessage(message: string) { return "Message from angular service"; } }

Here, @Injectable is a decorator in angular. The decorators help us provide ability to modify or use classes, method, properties and parameters. This injectable is just like a normal class. When we create an object of an injectable class, just like ngOnInIt() method, constructor will be executed.

@Injectable indicates here this particular class can be used with the dependency injector. If we want into inject service into other components, must define @injector() decorator.

The injectable service can’t be destroyed. If we want to remove instances of the service class, we need to remove the reference point of dependency injection of that class.

Now, let’s import in service class in our main module i.e. app.module.ts directly. Like,

import { BrowserModule } from "@angular/platform-browser"; import { NgModule } from "@angular/core"; import { AppComponent } from "./app.component"; import { GetMessageService } from "./getMessageService.service"; @NgModule({ declarations: [AppComponent], imports: [BrowserModule], providers: [GetMessageService], bootstrap: [AppComponent] }) export class AppModule {};

Here, we imported service class as providers. In @NgModule, we have four sections.

Declarations - Define imported components and directives

Imports- Define imported modules

Providers- Define imported services

Bootstrap- Define root component to display data

Now, let’s inject service class and get data from the service and display in UI i.e. app.component.ts file.

import { Component } from '@angular/core'; import { GetMessageService } from './getMessageService.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { message: string = ""; constructor(private msgService: GetMessageService ) {} ngOnInit() { this.message = this.msgService.showMessage (); } }

In app.component.html file

<p>Service example</p> <p>{{message}}</p>

Output

Service example
Message from angular service

Like this we can create custom services and we share the data with multiple components.

Above, we discussed about what are the services and what is the use of it. How to create them. Services mainly we used to share the common data or functionality with one or multiple components. With the services we can achieve code reusability.

Updated on: 21-Feb-2023

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements