Angular Data Services Using Observable

Introduction

In this article, we are going to see Observable manage async data and a few other useful patterns. Observables are similar to Promises but with some key differences. Promises and Observables emit multiple values over time. In real-time-based data or events, handlers can emit multiple values over any given time. In this case, Observables are the best option we can use.

In angular, Observables are one of the most used techniques. It is used extensively in integration with Data Services to read an API. Other than that, to access an observable, the component first needs to subscribe to the Observable. It is important to do this to access the data in observable.

Services in angular

Angular lets you define code or functionalities that are then accessible and reusable in many other components in your Angular apps.

The Services are used to create variable data that can be shared and used outside the component in which it is injected and called services. In angular services can be called from any component and data can be distributed to any component in the application.

First, we need to set up an angular application and follow the steps below.

To add a service, write the following command in the console.

ng g s service-name 
OR 
ng generate service-name 

Here I have created the service name test-data.service.ts

import {
    Injectable
} from '@angular/core';
@Injectable({
    providedIn: 'root'
})
export class TestDataService {
    constructor() {}
    Testclick() {
        console.log('Test Click');
    }
}

The app.component.ts code

import {
    Component
} from '@angular/core';
import {
    TestDataService
} from './testdata-service';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    constructor(private Data: TestDataService) {}
    TestClickMsg() {
        this.Data.Testclick()
    }
}

App.component.html

<body>
    <button (click)="TestClickMsg()">Test Click</button>
</body> 

HTML

Services With Observable

In combination, it is advisable to work with API. In the following example, there will be a Service in which an API will be accessed using the GET request feature provided in the HttpClientModule in Angular, which in turn returns an observable. This observable will be subscribed to by a component of the application and then show the values on the page.

The data.service.ts

import {
    Injectable
} from '@angular/core';
//Importing HttpClientModule for GET request to API
import {
    HttpClient
} from '@angular/common/http';
@Injectable({
    providedIn: 'root'
})
export class TestDataService {
    // making an instance for Get Request
    constructor(private http_instance: HttpClient) {}
    // function returning the observable
    getAPIData() {
        //API Call
        //return this.http_instance.get('https://xxxxxxxxxxxxxxxxxxxxxxxxxxx');
        return [{
            "id": 1,
            "first_name": "Test",
            "last_name": "Satheesh 1"
        }, {
            "id": 2,
            "first_name": "Test",
            "last_name": "Satheesh 2"
        }, {
            "id": 3,
            "first_name": "Test",
            "last_name": "Satheesh 3"
        }]
    }
}

Here I have commanded API calls and added some static lists for our reference.

The app.component.ts

import {
    Component
} from '@angular/core';
import {
    TestDataService
} from './testdata-service';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    // instantiation of local object and the TestData Service
    inst: Object | undefined;
    constructor(private Data: TestDataService) {}
    //Subscription of the TestData Service and putting all the
    // data into the local instance of component
    ngOnInit() {
        this.Data.getAPIData().subscribe((data: Object | undefined) => {
            this.inst = data;
        })
    }
}

App.component.html

<div *ngFor="let user of inst">
  <p>{{ user.first_name }} {{ user.last_name }}</p>
</div>

Services With Observable

Finally, I get the data from services using observable. I hope this article is most helpful for you.