Create your account

Already have an account? Login here

Create account

Angular 2 Services Tutorial - Understanding & Creating Them

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:

How to Create an Angular 2 Service

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. 

Step 1: Create the Service File

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.

 

Step 2: Import the Injectable Member

At the top of your new services file, add:

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

 

Step 3: Add the Injectable Decorator

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.

 

Step 4: Export the Services Class

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".

 

Creating a Service with the Angular-CLI

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.

 

Importing the Service to your Components

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.

 

Step 1: Import the Service to your Component

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';

 

Step 2: Add it as a Provider

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]
})

 

Step 3: Include it through depedency injection

In the constructor arguments of the component class, we include it through dependency injection:

constructor(private _exampleService: ExampleService) {

}

 

Step 4: Using the Service

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.

 

Including the Service in app.module.ts

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.

 


Share this post




Say something about this awesome post!