How it works: Angular Services

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.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade