Creating Service In Angular Using CLI/Manually

Manthan Ankolekar - Jul 22 '22 - - Dev Community

Create the Service using CLI

ng generate service <service-name>
Enter fullscreen mode Exit fullscreen mode

Structure :

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

@Injectable({
  providedIn: 'root',
})
export class <service-name> {

  constructor() { }

}
Enter fullscreen mode Exit fullscreen mode

Create the Service Manually

To create a new service manually:

  1. Navigate to your Angular project directory.
  2. Create a new file, <service-name>.service.ts
  3. At the top of the file, add the following import statement.
import { Injectable } from '@angular/core';
Enter fullscreen mode Exit fullscreen mode
  1. Add @Injectable() service
@Injectable({
  providedIn: 'root',
})
Enter fullscreen mode Exit fullscreen mode
  1. Add a class statement that includes the code for the component with constructor.
export class <service-name> {

  constructor() { }

}
Enter fullscreen mode Exit fullscreen mode
  1. Using service in component, first need to Inject in constructor like this :

    Add a private  ex : heroService parameter of type HeroServiceto the constructor.

// example
constructor(private heroService: HeroService) {}
Enter fullscreen mode Exit fullscreen mode
  Next Import :
Enter fullscreen mode Exit fullscreen mode
// example
import { HeroService } from '../hero.service';
Enter fullscreen mode Exit fullscreen mode
  1. Need to add in <app.module.ts> like this :
// example
@Component({
  /* . . . */
  providers: [HeroService]
})
Enter fullscreen mode Exit fullscreen mode

and import in it.

// example
import { HeroService } from '../hero.service';
Enter fullscreen mode Exit fullscreen mode

Reference :

Angular Service

Live Example :

Stack Blitz

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player