Rxjs Observable in angular with an example

Rxjs Observable in angular is the most basic building block of RxJS that represents an event emitter, which will emit any data received over time. The Observable object definition will not cause a networking event to be fired unless it will not subscribe or listened, observable are lazy in nature.
By calling .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 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.

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.”

Rxjs Observable in angular

We have to follow this step to set up HttpClient in our Angular project.
Step 1: Import HttpClientModule in the root module
Import 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: Inject HttpClient in service constructor and create employee service to access employee data in our application using observable rxjs.
Lets 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 observer which subscribe 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;
    });
  }
}

Step 6: In view, we will render our employees array as

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

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

Leave a Comment

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

Scroll to Top