By Gary simon - Oct 31, 2016
An Angular 2 service is simply a javascript function, along with its associated properties and methods, that can be included (via dependency injection) into Angular 2 components. They allow you to develop code for specific tasks that can be used in those components.
First, if you prefer watching a video on this subject, check out this video we created here:
There are 2 ways to create an Angular 2 service; the manual method, and then through the Angular CLI (Command Line Interface). The Angular CLI method of course is easy, so we will cover that after showing you how to build one from scratch.
In your code editor, create a file consistent with the following naming convention:
name.service.ts
"name" can be a name that's relevant to your service. ".service.ts" always remains the same. You can place this file in the app folder, or in its own folder off of the app folder.
At the top of your new services file, add:
import { Injectable } from '@angular/core';
In step 2 above, we imported the Injectable member from the Angular Core library. Now we need to add the Injectable() decorator:
@Injectable()
Note: As with all other Angular decorators, we preceed the name with an @ symbol, and we do not add a semi-colon ; at the end.
And finally, we create the class that contains the logic of our service:
export class ExampleService {
// This is where your methods and properties go, for example:
someMethod() {
return 'Hey!';
}
}
Note ExampleService - This is Pascal case. If you name your service file "myservice.service.ts", then your exported class should be: "Myservice".
This is fairly easy, as it generates the scaffolding for you. In the command prompt, simply type:
ng generate service myservicename
This will generate a myservicename.service.ts file within the app folder that contains the scaffolding from steps 1-4 above.
You can either import your service directly within the components, or you can import them to the app.module.ts file, which will give all of your components access to that service. We'll show you both ways.
Choose a component file and at the top, you must include the service member (line 2 below):
import { Component } from '@angular/core';
import { ExampleService } from './example.service';
Now you must add it to the providers array in the Component decorator metadata (line 4 below):
@Component({
selector: 'my-app',
template: '<h1>{{ title }}</h1>',
providers: [ExampleService]
})
In the constructor arguments of the component class, we include it through dependency injection:
constructor(private _exampleService: ExampleService) {
}
Now we can access the service's methods and properties by referencing the private _exampleService. For example:
ngOnInit() {
this.title = this._exampleService.someMethod();
}
Here's the full code of the service above, along with the component.
example.service.ts:
import { Injectable } from '@angular/core';
@Injectable()
export class ExampleService {
someMethod() {
return 'Hey!';
}
}
app.component.ts:
import { Component } from '@angular/core';
import { ExampleService } from './example.service';
@Component({
selector: 'my-app',
template: '<h1>{{ title }}</h1>',
providers: [ExampleService]
})
export class AppComponent {
title: string;
constructor(private _exampleService: ExampleService) {
}
ngOnInit() {
this.title = this._exampleService.someMethod();
}
}
This will result in "Hey!" showing up within the h1 tag.
The only step that differs when including a service in the app.module.ts from including it in a specific component is that you're declaring the service in the providers property of the app.module.ts @NgModule metadata, as opposed to the @Component's meta data:
In app.module.ts:
// other imports in app.module.ts
import { ExampleService } from './example.service';
@NgModule({
//other metadata properties
providers: [ExampleService]
})
Now all Components within our application will have access to ExampleService. We no longer need to include ExampleService in a providers array within the component's metadata. We do still need to import the ExampleService at the top of the components that we wish to use.