Create the Service using CLI
ng generate service <service-name>
Structure :
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class <service-name> {
constructor() { }
}
Create the Service Manually
To create a new service manually:
- Navigate to your Angular project directory.
- Create a new file,
<service-name>.service.ts
- At the top of the file, add the following import statement.
import { Injectable } from '@angular/core';
- Add @Injectable() service
@Injectable({
providedIn: 'root',
})
- Add a
class
statement that includes the code for the component with constructor.
export class <service-name> {
constructor() { }
}
-
Using service in component, first need to Inject in constructor like this :
Add a private ex :
heroService
parameter of typeHeroService
to the constructor.
// example
constructor(private heroService: HeroService) {}
Next Import :
// example
import { HeroService } from '../hero.service';
- Need to add in
<app.module.ts>
like this :
// example
@Component({
/* . . . */
providers: [HeroService]
})
and import in it.
// example
import { HeroService } from '../hero.service';
Reference :
Live Example :