How To Create An Angular Service And Access It In Multiple Components

In our previous article, we developed a single page application using Angular 4. Now, in this article, we are going to talk about Angular services. If we want to share the data among components, then we need to create a service.

From this article, you will be able to learn the below concepts with practical examples.

  1. How to create a service?
  2. How to create a function in service
  3. How to access service in default component
  4. How to access service in multiple components?
  5. Benefits of implement services in multiple components?

We want to create a function to solve the data of an array.

Let us define a service and write that function in that service, and from that service, we can access the data in multiple components, rather than adding a function in each component which makes a lot of duplications of the same code.

First of all, we need to create a service and to create it refer to the below table.

Scaffold Command
Component ng g component my-new-component
Directive ng g directive my-new-directive
Pipe ng g pipe my new-pipe
Service ng g service my new-service
Class ng g class my new-class
Interface ng g interface my new- interface
Enum ng enum my new-enum
Module ng g module my-module

From the above table, we can see the command to create a service as below,

  1.  ng g service (name of service).

Let's come back to command prompt and make sure the directory points to your project folder and execute the command to create a service.

Angular

From above screenshot I named my service as myData and click enter.

Success

Angular

Service name in project folder as below,

Angular

Open my-data.service.ts, there will a class named MydDataService in which we will be writing service function.

In this service, we need to create a few functions, any object or any variable.

So, first of all we need to add this service in our module.

Open app.module.ts file and write below line after import{ AppComponent} as shown below,

import { MyDataService } from './my-data.service';

Screenshot

Angular

Next copy the service name and paste in Providers in same file app.module.ts.

Angular

Now go to service and create a function after the constructor and name the function name as success as below.

Code

  1. import {  
  2.     Injectable  
  3. } from '@angular/core';  
  4. @Injectable()  
  5. export class MyDataService {  
  6.     constructor() {}  
  7.     success() {  
  8.         return "Successfull";  
  9.     }  
  10. }  

Above the success function, let create an object as below,

Code

  1. import {  
  2.     Injectable  
  3. } from '@angular/core';  
  4. @Injectable()  
  5. export class MyDataService {  
  6.     constructor() {}  
  7.     obj = {  
  8.         id: "4720",  
  9.         name: "Rathrola Prem Kumar",  
  10.         position: "Software Engineer"  
  11.     }  
  12.     success() {  
  13.         return "Successfull";  
  14.     }  
  15. }  

Now I need to use this object and success function outside variables with in the components.

Open Components.ts and write import statement same as in app.module.ts,

import { MyDataService } from './my-data.service';

So now in order to use this service within the component, we have to create constructor function and let’s capture the message using console.log as shown below,

Code

  1. import {  
  2.     Component  
  3. } from '@angular/core';  
  4. import {  
  5.     MyDataService  
  6. } from './my-data.service';  
  7. @Component({  
  8.     selector: 'app-root',  
  9.     templateUrl: './app.component.html',  
  10.     styleUrls: ['./app.component.css']  
  11. })  
  12. export class AppComponent {  
  13.     constructor(private newService: MyDataService) {}  
  14.     ngOnInit() {  
  15.         log(this.newService.success);  
  16.     }  
  17. }  

Output

Angular

So our service function has been accessed within our component.

Let’s try to access our variable now as below

Code

log(this.newService.obj);

Output

Angular

Obj has been fetched from that service within our component.

Now as we discussed, we can share the data among different components.

Right now app.component.ts is a default component, create a new component and copy the import service line and paste in new component as shown below.

Note

Here my new component name is my-component.

Code

  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. import {  
  6.     MyDataService  
  7. } from './../my-data.service';  
  8. @Component({  
  9.     selector: 'app-my-component',  
  10.     templateUrl: './my-component.component.html',  
  11.     styleUrls: ['./my-component.component.css']  
  12. })  
  13. export class MyComponentComponent implements OnInit {  
  14.     constructor(private newService: MyDataService) {}  
  15.     ngOnInit() {  
  16.         log(this.newService.success());  
  17.     }  
  18. }  

In order to use this new component, we need to add its selector in html template of our default component.

Output

Angular

The first and second messages are from app.component.ts and the third one is from another component which is from my-component.

So we are able to access the service among multiple components.

The advantage of doing it this way is that, if we change anything in any of these components, it will also reflect the change in other components. Because the service is independent, that service will have only one instance.

So finally you learned about the services in Angular 4, thanks for reading my article J


Similar Articles