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';
export class ExampleServiceService {
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

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
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';
declarations: [
imports: [
providers: [ExampleServiceService],
bootstrap: [AppComponent]
export class AppModule { }

Angular Service Example

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


 <script src=""></script>
 <script src=""></script>
 <script src=""></script>
 <script src=""></script>
 <script src="app.js"></script>
 <script src="anotherModule.js"></script>
 <div ng-app="mainModule" ng-controller="mainController as alias">
 <p>The input is: {{alias.quantity}}</p>
 Quantity: <input type="number" min="0" ng-model="alias.quantity"required>
 <div><p>Add 4 and double it!</p></div>
 <button class="btn" ng-click="alias.paid(">Pay</button>


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

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

  this.paid = function pay(parameter) {



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.