HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Angular / Angular Service Example

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 !!

Sourcecode Download

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Angular Tutorial

  • Angular – Workspace Setup
  • Angular – Npm install hung
  • Angular – Mock REST Server
  • Angular – Interpolation
  • Angular – Components
  • Angular – Templates
  • Angular – Services
  • Angular – RxJS Observable

AngularJS Tutorials

  • AngularJS – HelloWorld Example
  • AngularJS – jQuery Lite
  • AngularJS – Services
  • AngularJS – RESTful API Example

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces