Angular Service Example

Learn to create Angular service and import service as global dependency (via module) vs local dependency (via component) with example.

Table of Contents

Create Service
Global service vs Local Service Injection
Demo

Create Service

Create a new file calc.service.ts in desired location and put following code in it. CalcService is the service name.

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

@Injectable({
  providedIn: 'root'
})
export class CalcService {

  constructor() { }

}

Above service is very much complete and ready to be consumed in application components.

Using Angular CLI

Creating service is easy if you use Angular CLI. It is just one command which does the all work. It will generate the service code just like above example.

$ ng g s service/calc --flat 

//Other useful options

--force  = override
--spec=false = dont generate spec file
--dry-run = dont touch code if it has been updated already.

Global service vs Local Service Injection

To inject the service, you have two options.

1) Inject as ‘global service’

To inject as global service, inject the service into root module.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { CalcService } from './service/calc.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [CalcService],
  bootstrap: [AppComponent]
})
export class AppModule { }

2) Inject as ‘local service’

To inject as local service, inject the service into component directly.

import { Component } from '@angular/core';
import { CalcService } from './service/calc.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [CalcService]
})
export class AppComponent {
  title = 'app';

  constructor(calc:CalcService){
   	//Use calc
  }
}

Demo

1) Add a method to service

To demonstrate the usage of CalcService, let’s define a new method in service and use it in app.component.ts.

I have added method add() which takes REST parameter as array of numbers. It then add all numbers and return the sum.

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

@Injectable({
  providedIn: 'root'
})
export class CalcService {

  constructor() { }

  public add(...params: number[]): number {
    let result = 0;
    for (let val of params) {
        result += val;
    }
    return result;
  }
}

2) Import service to compoment and use the method to update model

I created a new model attribute 'sum' which we will update with return value of service method add().

import { Component } from '@angular/core';
import { CalcService } from './service/calc.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  sum: number = 0;
  constructor(calc:CalcService){
    this.sum = calc.add(1,2,3,4);
  }
}

3) Update view HTML

Now finally, update view html file with newly added model attribute sum.

<h1>
	Welcome to {{ title }}!
	Sum is {{sum}}
</h1>

4) Run the app

Now run the app with command 'ng serve' and check the output at 'http://localhost:4200/'.

Angular 2 service output
Angular 2 service output

Drop me your questions in comments section.

Happy Learning !!

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial