Angular 4: Building a Simple Service

Create the project with angular-cli

$ ng new angular-service-project

Create a service with angular-cli

The service was created with,

$ ng g s example-service

where ‘g’ is a shortcut for ‘generate’ and ‘s’ is a shortcut for ‘service’.

The actual service is at: example-service-service.ts

import { Injectable } from '@angular/core';
@Injectable()
export class ExampleServiceService {
someMethod(){
return "Heya!";
}
constructor() { }
}

Then make the changes to app.component.ts

import { Component, OnInit } from '@angular/core'; // added OnInit
import { ExampleServiceService } from './example-service.service' // added this import

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [ExampleServiceService]
})
export class AppComponent {
title = 'app works!';
example: string;
constructor(private _exampleServiceService: ExampleServiceService){ // added this constructor
}
// added this ngOnInit method
ngOnInit(){
this.example = this._exampleServiceService.someMethod();
}
}

Get example into the app.component.html file,

<h1>{{ title }}</h1>
<h3>{{ example }}</h3>

To make this service available to all components, cut the line

providers: [ExampleServiceService]

from app.component.ts and put it is app.module.ts and also make it available with

import { ExampleServiceService } from './example-service.service'

app.module.ts should look like this,

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { ExampleServiceService } from './example-service.service'
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [ExampleServiceService],
bootstrap: [AppComponent]
})
export class AppModule { }

Angular Service Example

The following code demonstrates how a service can be created in AngularJS.

index.html

<html>
 <head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-route.min.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.min.js"></script>
 <script src="app.js"></script>
 <script src="anotherModule.js"></script>
 </head>
 <body>
 <div ng-app="mainModule" ng-controller="mainController as alias">
 <b>Invoice:</b>
 <p>The input is: {{alias.quantity}}</p>
 <div>
 Quantity: <input type="number" min="0" ng-model="alias.quantity"required>
 </div>
 <div><p>Add 4 and double it!</p></div>
 <div>
 <b>Result:</b>
 <span>{{alias.total(alias.quantity)}}</span>
 <button class="btn" ng-click="alias.paid(alias.total(alias.quantity))">Pay</button>
 </div>
 </div>
 </body>
</html>

app.js

angular.module('mainModule', ['dependencyModule'])
.controller('mainController', ['theService', function(theService) {

  this.quantity = 1;

  this.total = function total(number) {
    return theService.inService(number + 4);
  };

  this.paid = function pay(parameter) {
    window.alert(parameter);
  };

}]);

anotherModule.js

angular.module('dependencyModule', [])
  //currencyConverter is the service
.factory('theService', function() {

  var functionInService = function (parameter2) {
    return parameter2 * 2;
  };

  return {
    inService: functionInService
  };
});

Services can be used to share code across controllers.