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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s