Service Injection with Angular 2

Note: This post is based heavily on the Angular 2 tutorial, Services, hopefully I can add something useful to this.

We all know what dependency injection is about, right?

Let’s see how we create and inject services using Angular 2.

Naming convention

With components, the convention is to create a TypeScript component class suffixed with the work Component, hence our detail component class would be named DetailComponent and likewise the convention with regards to the file naming is to name file detail.component.ts (all lower case).

We use a similar convention for services. The TypeScript class might be named MyDataService therefore our file would be my-data.service.ts

Note: the hyphen between word boundaries and ofcourse replacing component with service.

Creating our service

Let’s create a simple data service. As per our naming convention, create a file named my-data.service.ts and here’s the code

import { Injectable } from '@angular/core';

@Injectable()
export class MyDataService {
   // methods etc. omitted
}

To quote the Angular 2 documentation

The @Injectable() decorator tells TypeScript to emit metadata about the service. The metadata specifies that Angular may need to inject other dependencies into this service.

Using the service

In the code that uses the service we still need to import the service (as obviously we need a reference to the type) but instead of our component/code creating the service, we leave this to Angular 2. So the usual would be to create a constructor and allow Angular 2 to inject our service via the constructor. For example here’s the bare bones for a DetailsComponent that uses the previously implemented service

// other imports omitted
import { MyDataService } from './my-data.service';

@Component({
   // selector etc. 
   providers: [MyDataService];
})
export class DetailsComponent {
   constructor(private myDataService: MyDataService) {
   }
}

Notice we also need to register our service in the providers array either within the component or within the app.modules.ts inside the @NgModule.

If the service is registered with providers in a component, then an instance is created when the component is created (and is available for any child components), whereas registering within @NgModule would be more like creating a singleton of the service as the service would be created when the module is created and then available to all components.