Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Angular observable with an example in Angular 12

Angular observable example

Rxjs Observable is the most basic building block of RxJS that represents an event emitter, which will emit any data received over time. Angular Observable object definition will not cause a networking event to be fired unless it will not subscribe or listen, as observables are lazy in nature.

By calling Angular to subscribe on the Observable, you’re essentially attaching a listener to the emitter. You’ve implemented an anonymous function within the subscribe method, which will get executed whenever a new piece of data is received and an event is emitted.

Angular observable example
Angular observable example

Setting up and configuring Angular observable project

Angular HttpClient with RxJS Observable example to access local JSON data. Most front-end applications communicate with backend services over the HTTP protocol. Modern browsers support two different APIs for making HTTP requests:

  1. XMLHttpRequest interface
  2. fetch() API.

Step 1: Create Angular observable example project
Let’s first create an angular observable example project by running the following command.

ng new observableApp
cd observableApp

Step 2: Import HttpClientModule in the app.module.ts file

The HttpClient in @angular/common/http offers a simplified client HTTP API for Angular applications that rests on the XMLHttpRequest interface exposed by browsers. HttpClient service to fetch data from online REST APIs and return it as an Observable object/array. Upon any data event, the subscribers of observable will react.

Here is a screenshot of the Angular observable example to retrieve data using observable.

Angular Observable example
Angular observable example

We have to follow this step to set up HttpClient in our Angular project.

Step 1: Import HttpClientModule in the root module
Import the HttpClientModule module from @angular/common/http package and add it’s an entry in the import attribute of @NgModule.

import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
....
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule
  ],
  providers: [
	...
  ],
  bootstrap: [AppComponent]
})
export class AppModule

Step 2: Create an employee model to create an observable type so we can have autocompleted and reduced errors in our code.

export interface IEmployee {
    name: string;
    company: string;
}

Step 3: Add dummy JSON employee data in assets/data/employees.JSON

[  
    {"name":"Ram", "company":"Google"},  
    {"name":"Bob", "company":"EMC"},
    {"name":"Ram", "company":"Google"},  
    {"name":"Bob", "company":"EMC"},
    {"name":"Ram", "company":"Google"},  
    {"name":"Bob", "company":"EMC"}  
]

Step 4: Create Observable service
Inject HttpClient in the service constructor and create employee service to access employee data in our application using observable rxjs. Let’s first generate employee service

ng generate service employee

HttpClient is Angular’s mechanism for communicating with a remote server over HTTP. All HttpClient methods return an RxJS Observable in angular of something. In general, an observable can return multiple values over time. An observable from HttpClient always emits a single value and then completes, never to emit again.

import { IEmployee } from './employee.model';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
  constructor(private httpClient: HttpClient) {}

  getEmployees(): Observable<IEmployee[]> {
    return this.httpClient.get<IEmployee[]>('./assets/data/employees.json');
  }
}

Step 5: Create an observer which subscribes to Observable
In our angular project, we will create a subscriber in the component file. It will read the data from the observable array and assign it to the model attribute. The model attribute can be used to map data from UI.

import { Component, OnInit } from '@angular/core';
import { IEmployee } from './employee.model';
import { EmployeeService } from './employee.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  employees: IEmployee[];
  constructor(private employeeService: EmployeeService) { }

  ngOnInit() {
    this.employeeService.getEmployees()
    .subscribe((data: IEmployee[]) => {
      this.employees = data;
    });
  }
}

As observable by definition will not invoke, until Angular subscribes to our observable. We had to add Angular subscribe on the getEmployees() method of employee Service.

Step 6: In view, we will render our employee’s array as

 <div *ngFor="let employee of employees">
	<h4>{{ employee?.name }}</h4>
	<h4>{{ employee?.company }}</h4>
</div>

observable vs promise

In Angular application, we have to use observable and promise extensively to perform asynchronous activities. Here we have listed the differences between Observable and promise.

Observable Promise
An Observable is like a Stream and allows to pass zero or multiple events over a period of time.Promise handles a single event when an async operation completes or fails.
Observable also has the advantage over Promise, as observable can be cancellable.Are not cancellable.
Observability only starts if we subscribe to it. This is why Observables are called lazy.While a Promise starts immediately after its creation. Are not lazy.
Observable provides operators like map, forEach, reduce, pipe, and more. This is because observable lazy in nature, allows us to build up a chain of operators before the observable is executed by subscribing, to do a more declarative kind of programming.Don’t provide any operations like map, reduce, and pipe
Angular Observable vs Promise

How to convert promise to observable

In an Angular we can easily convert promise to observable and here we had demonstrated an example. You can convert it based on your requirement.

getProducts(page: number): Observable<any> {
  return new Observable((observer) => {
   this.wooCommerce.getAsync('products').then((data) => {
     observer.next(JSON.parse(data.body));
     observer.complete();
    }).catch((error) => {
       console.error(error);
       observer.error();
    });
  });
}

To check more information on the angular service on the official documentation site.

Check articles on the best and latest 2022, and 2021 Angular books to read for your journey from beginner to advanced level. BEST BOOK ON ANGULAR 2022 – 2021

Related Post

Angular observable with an example in Angular 12

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top