Angular 6+
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor() {
}
}
Angular 5
Method 1. add class in app.module.ts
's providers
@NgModule({
// ----
providers: [
MyService // added class in the providers
]
// ----
})
export class AppModule { }
Method 2.
add class in component
's provider
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss'],
providers: [
MyService // added class in the providers
]
})
export class MyComponent {
constructor(private service: MyService) {
}
}
Important: Please don't forget to annotate the class as @Injectable
so that you can inject it in the constructor i.e.
import { Injectable } from "@angular/core";
@Injectable() // class annotation as Injectable
export class MyService {
constructor() {
}
}