Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to inject service in angular 6 component ?

  • Last Updated : 01 Jul, 2021

Service is a special class in Angular which is primarily used for inter-component communication. Sometimes there are components that need a common pool to interact with each other mostly for data or information procurement. Service makes it possible. The two (or more) components may or may not be related to each other. That means there may exist a parent-child relationship or nothing at all.

Services and other dependencies are injected directly into the constructor of the component like this:

constructor(private _myService: MyService) {
}

By doing this, we are actually creating an instance of the service. That means we have to access all the public variables and methods of the service.

To create a new service, we can use the code scaffolding tool:

// Generate service
ng g s my-custom-service

Injecting a service into a component is pretty straightforward. Let’s say we have a service called MyCustomService. This is how we can inject it into a component:



MyCustomComponent.ts




import {...} from "@angular/core";
import { MyCustomService } from "../...PATH";
  
@Component({
  selector: "...",
  templateUrl: "...",
  styleUrls: ["..."],
})
export class MyCustomComponent {
  
    // INJECTING SERVICE INTO THE CONSTRUCTOR
    constructor(private _myCustomService: MyCustomService) {}
    
      // USING THE SERVICE MEMBERS
    this._myCustomService.sampleMethod();
}

This may not make any sense until and unless we get our hands dirty. So let’s quickly create a service and see how it is injected and can be accessed easily. For this demo, we will create two simple custom components. Let’s say, Ladies and Gentlemen. There is no parent-child relationship between these two components. Both are absolutely independent. Gentlemen will greet Ladies with “Good morning” with the click of a button. For this, we will use a service that will interact between the two components. We will call it InteractionService.

First thing first, we will create our 2 components and 1 service.

Now we have everything that we need. Since this demo is particularly for service injection. We will not discuss the components in detail. Let’s start with service first. Here is the code:

interaction.service.ts




import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
  
@Injectable({
  providedIn: 'root'
})
export class InteractionService {
  private _messageSource = new Subject<string>();
    
  greeting$=this._messageSource.asObservable();
    
  sendMessage(message: string) {
    this._messageSource.next(message);
  }
}

This been done. We will now inject this service into both our components.

gentlemen.component.html




<!DOCTYPE html>
<html>
  <head>
      <title>Page Title</title>
  </head>
  <body>
      <h2>Welcome To GFG</h2>
      <button (click)="greetLadies()">Greet</button>
  </body>
</html>

We will now create the first component using:




// Generate component
ng g c gentlemen

gentlemen.component.ts




import {...} from "@angular/core";
...
import { InteractionService } from "../services/interaction.service";
  
@Component({
  selector: "app-gentlemen",
  templateUrl: "./gentlemen.component.html",
  styleUrls: ["./gentlemen.component.scss"],
})
export class GentlemenComponent {
  
  // SERVICE INJECTION
  constructor(private _interactionService: InteractionService) {}
  
  greetLadies() {
    this._interactionService.sendMessage("Good morning");
  }
}

Quickly create our last component:




// Generate component
ng g c ladies

ladies.component.ts




import {...} from "@angular/core";
...
import { InteractionService } from "../services/interaction.service";
  
@Component({
  selector: "app-ladies",
  templateUrl: "./ladies.component.html",
  styleUrls: ["./ladies.component.scss"],
})
export class LadiesComponent implements OnInit {
    
  // SERVICE INJECTION
  constructor(private _interactionService: InteractionService) {}
  
  ngOnInit() {
    this._interactionService.greeting$.subscribe(message => {
      console.log(message);
    })
  }
}

This is how we can inject and use the service to interact between components. We just saw a use case of service injection. 

We will have this as our final product:

UI/UX Screenshot

On click on buttons we can expect the following output:

Expected output




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!