In this exercise we will demystify the Angular Service by taking a simple pragmatic approach to implementing a service that retrieves a JSON file from the server using the HttpClientModule.

The notion of Services is that of a “Design Pattern”. At the end of the day a Service is nothing more than a class. What makes it fancy is combining it with Dependency Injection (DI) which handles instantiation & construction for us.

What is AngularJS?

Coincidentally Services are “Singletons”. Meaning that they will only be instantiated once within the current context. By injecting a Service in multiple locations such as a parent & child component you can effectively share the state of objects.

Why should I use a service?
Anytime you want to provide re-usability at the logic level you should wrap it into a service. By de-coupling your logic from the scope of Component Classes you maintain “Separation of Concerns”. Doing so will

Declaring a Service
ng generate service


import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable, Subject} from 'rxjs';

    providedIn: 'root'
export class FormsService {

    public constructor(private httpClient: HttpClient) {

Web Application Development using Loopback Ionic Angular


    public getFormSchema(): Observable {

        let subject: Subject = new Subject();

        this.httpClient.get('assets/form-schema.json').subscribe((results: any) => {




        return subject;


 Consuming a Service
In this example we will use “Dependency Injection” to be able to call our services getFormSchema() method:

/src/app/ app.component.ts

import {Component} from '@angular/core';
import {FormsService} from './forms.service';

    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
export class AppComponent {

    public constructor(private formsService: FormsService) {

        formsService.getFormSchema().subscribe((results: any) => {





What you pick in 2018 : ReactJS vs AngularJS vs VueJS