How it works: Angular Services
Jul 23, 2017 · 1 min read
Angular services are classes that perform operations, for example you can have AuthService class that will handle the user login making requests to an API.
import { Injectable } from '@angular/core';
@Injectable()
export class AuthService {
constructor() { }
}Services are decorated with @Injectable. This decorator generates metadata that is used later to inject dependencies. They are added in the module providers array:
@NgModule({
...
providers: [AuthService],
})And then they can be retrieved in a component:
@Component({ ... })
export class LoginComponent {
constructor(private auth: AuthService) { }
}When testing you can retrieve services in two ways:
TestBed.get(AuthService);
// or
inject([AuthService], (authService) => { });Angular How it works series
Check out other posts of this series, Angular How it works.
