Angular 2 Service


Angular 2 Services

Angular 2 service is a special class that can be included via Angular dependency injection. The main intention of Angular 2 Service is to develop code for specific tasks.

For example we have one database connection and we want to reuse it later in another Module using dependency injection.

The name of Service should be end with “.service.ts” always.

Steps to create Angular Service

  1. Create Service class file (ServiceName.service.ts).
  2. Import the Injectable from ‘@angular/core’
  3. Add the @Injectable Decorator at Service class level.
  4. Write your required logic inside service class and export service class using export keyword.

name.service.ts

import { Injectable } from '@angular/core';  

@Injectable()
export class NameService {  
   getName(): string { 
      return "Vikas Kumar"; 
   } 
}

Once you have created Service then you can use it in another Angular module.

To be able to use Angular service class in another component class we have declare in providers section like below

import { NameService } from './name.service';
@Component({
    selector: 'stude-name',
    templateUrl: './stud-name.html',
    providers: [NameService]
})

Once you declared your service class inside providers then you can get service object through dependency injection inside Component constructor as an arguments like below.

export class DisplayComponent { 
   constructor(private _nameService: NameService) {
   }  
}

Now we can use service method inside angular component like below.

export class DisplayComponent { 
   name: string = ""; 
   constructor(private _nameService: NameService) { }  

   ngOnInit(): void { 
      this.name= this._nameService.getName(); 
   } 
}






Full-stack web and mobile app development company Contact Us : Skype: indore.webcoder Email: info@w3sparks.com Sales: +91 8085506229