Open In App

How to inject service in angular 6 component ?

Last Updated : 02 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Service is a special class in Angular that is primarily used for inter-component communication. It is a class having a narrow & well-defined purpose that should perform a specific task. The function, any value, or any feature which may application required, are encompassed by the Service. In other words, 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. 

Basically, Service helps to organize & share the business logic, data model & functions with various components in the application, & it gets instantiated only once in the lifecycle of the application. For this, Services is written only once & can be injected into the different components, which use that particular Services.

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, which means we have to access all the public variables and methods of the service.

Syntax: To create a new service, we can use the below command:

// Generate service
ng generate sservice my-custom-service

Injecting a service into a component is pretty straightforward. For instance, suppose we have a service called MyCustomService. This is how we can inject it into a component:

 

  • MyCustomComponent.ts

Javascript




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();
}


Before we proceed to inject the Service into the Component, we need to set up as many Components, as required. Please refer to the Components in Angular article for the detailed installation of the components in the application. Now, we have everything that we need. Since this demo is particularly for service injection.

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, 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. We will now create the first component using the following command:

ng generate component gentlemen

Quickly create our last component:

ng generate component ladies

Project Structure: The following structure will appear after completing the installation procedure:

 

Example: This example describes the injection of Service in the angular 6 components.

  • interaction.service.ts

Javascript




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 has been done. We will now inject this service into both our components.

  • gentlemen.component.html

HTML




<h1>GeeksforGeeks</h1>
<h3>
      Injecting the Service in Angular 6 Component
</h3>
<p>I am a Gentleman</p>
<button (click)="greetLadies()">
      Greet1
</button>
<button (click)="greetLadies1()">
      Greet2
</button>


  • gentlemen.component.ts

Javascript




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


  • gentleman.component.css

CSS




h1 {
    color: green;
}


  • ladies.component.ts:

Javascript




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


  • app.component.html

HTML




<app-gentlemen></app-gentlemen>
<app-ladies></app-ladies>


  • app.component.ts

Javascript




import { Component } from '@angular/core';
  
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'MyProject';
}


  • app.module.ts

Javascript




import { NgModule } from '@angular/core';
import { BrowserModule } 
    from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { GentlemenComponent } 
    from './gentlemen/gentlemen.component';
import { LadiesComponent } 
    from './ladies/ladies.component';
  
@NgModule({
    declarations: [
        AppComponent,
        GentlemenComponent,
        LadiesComponent
    ],
    imports: [
        BrowserModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }


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

Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads