Angular 8 Tutorial: Observable and RXJS Examples

by Didin J. on Oct 13, 2019 Angular 8 Tutorial:  Observable and RXJS Examples

Learning Angular 8 Observable and RXJS with examples that might be useful for building Angular application

In this Angular 8 tutorial, we will show you how to learn or understand Angular 8 Observable and RxJS by a few examples. Maybe you already know that Observable and RxJS use with HttpClient. This time, we will show you the example of Angular Observable and RxJS with HttpClient, data exchange between components, Async pipe, Router, and Reactive Forms.

Table of Contents:

Angular Observable use as an interface to handle a variety of common asynchronous operations such as send observable data from child to parent component by defining custom events, handle AJAX or HTTP requests and responses, listen and respond user input in Angular Router and Forms. RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code. The following tools, frameworks, and libraries or modules are required for this tutorial.

  1. Node.js
  2. Angular 8
  3. Terminal (Linux/Mac) or Node Command Line (Windows)
  4. Text Editor or IDE (We use VSCode)


Preparation

To make all examples runnable, we need to prepare an Angular 8 application to implements all Angular Observable and RxJS. We are creating an Angular 8 app using Angular CLI which needs Node.js and NPM to install or update it. Make sure you have to install Node.js and NPM before installing or updating Angular CLI. To install or update an Angular CLI type this command.

sudo npm install -g @angular/cli

Next, create a new Angular 8 app using Angular CLI by type this command.

ng new angular-observable-rxjs

That command will create a new Angular 8 app with the name `angular-observable-rxjs` and pass all questions as default then the Angular CLI will automatically install the required NPM modules. After finished, go to the newly created Angular 8 folder then run the Angular 8 app for the first time.

cd ./angular-observable-rxjs
ng serve --open

Using that "--open" parameters will automatically open the Angular 8 in your default web browser. Here's the Angular 8 default page look like.

Angular 8 Tutorial:  Observable and RXJS Examples - Home Page


Basic Angular Observable and RxJS

In Angular Observable, there are a publisher and subscriber. The publisher can create an Observable instance that defines a subscriber function. The subscriber is receiving notification by executing the observable using subscribe() method and stop receiving the notification using the unsubscribe() method. To practice a Basic Angular Observable and RxJS we will use existing `src/app/app.component.ts`. Open and edit that file to implement these basic examples.

Observe Timer Example

This example demonstrates the basic usage model by showing how the RxJS timer works by subscribing it and stopped after unsubscribing it. Add this import of RxJS timer.

import { timer } from 'rxjs';

Add a constant variable after the imports that declare the RxJS timer.

const source = timer(1000, 2000);

Subscribe the RxJS timer then print out to Javascript console.

const subscribe = source.subscribe(val => console.log(val));

Add a function that will unsubscribe the RxJS timer.

setTimeout(() => { subscribe.unsubscribe(); }, 10000);

Now, you will see the timer print the increased steps and stopped after 10 seconds.

Angular 8 Tutorial:  Observable and RXJS Examples - Output Console

Basic Subscribing using Observer

This example shows an example of subscribing using Observer. Add this RxJS `of` operator.

import { of } from 'rxjs';

RxJS `of` operator used to emit a variable amount of values in a sequence and then emits a complete notification. Next, declare a constant variable before the Angular @Component that contains the sequence of observable string that will emit using RxJS `of` operator.

const myObservable = of('apple', 'orange', 'grappe');

Add a constant observer object variable after the above constant.

const myObserver = {
  next: (x: string) => console.log('Observer got a next value: ' + x),
  error: (err: string) => console.error('Observer got an error: ' + err),
  complete: () => console.log('Observer got a complete notification'),
};

Inside the class, the body adds a constructor that will execute the observable by subscribing to the above observer object.

constructor() {
  myObservable.subscribe(myObserver);
}

That observable subscribing example will show output like this.

Observer got a next value: apple
app.component.ts:11 Observer got a next value: orange
app.component.ts:11 Observer got a next value: grappe
app.component.ts:13 Observer got a complete notification
core.js:38780 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
client:52 [WDS] Live Reloading enabled.

Observable with Constructor Example

We can use the observable constructor to create an observable stream of any type. The observable’s subscribe() executes with the constructor argument. The Observer object received by a subscriber function then publishes values using the observer's next() method. Add or modify the RxJS import to add Observer function.

import { Observable } from 'rxjs';

Add a function that runs the sequence of string synchronously then unsubscribe after values completed delivered.

function sequenceSubscriber(observer) {
  observer.next('Apple');
  observer.next('Orange');
  observer.next('Grappe');
  observer.complete();

  return {unsubscribe() {}};
}

Instantiate Observable that will deliver the above sequence of string.

const sequence = new Observable(sequenceSubscriber);

Execute the observable by print out the string sequence to the Javascript console.

sequence.subscribe({
  next(msg) { console.log(msg); },
  complete() { console.log('Finished sequence'); }
});

The Observable that Publishes Events Example

This example is taken from the official Angular docs with a little modification to work in `src/app/app.component.ts`. First, add an HTML input element to the existing `src/app/app.component.html`.

<div>
  <input type="text" id="yourname" placeholder="Type your name here"/>
</div>

Back to `src/app/app.component.ts`, modify this import to add Angular AfterViewInit lifecycle interface.

import { Component, AfterViewInit } from '@angular/core';

Implement that AfterViewInit in the main class.

export class AppComponent implements AfterViewInit {
...
}

Add a function that executes the Observable of the event from the target element.

fromEvent(target: HTMLInputElement, eventName: string) {
  return new Observable((observer) => {
    const handler = (e: unknown) => observer.next(e);

    target.addEventListener(eventName, handler);

    return () => {
      target.removeEventListener(eventName, handler);
    };
  });
}

Add ngAfterViewInit() function call the above function to create an observable that publishes key-down events.

ngAfterViewInit() {
  const ESC_KEY = 27;
  const nameInput = document.getElementById('yourname') as HTMLInputElement;
  this.fromEvent(nameInput, 'keydown')
  .subscribe((e: KeyboardEvent) => {
    if (e.keyCode === ESC_KEY) {
      nameInput.value = '';
    }
  });
}

Now, every ESC key push in the HTML input element, it will clear the input value.


Observable and RxJS with HttpClient

Almost our Angular tutorial involves REST API requests using Angular HttpClient, Observable, and RxJS. So, this example is a combination of these Angular features. This time we will put all in `src/app/app.component.html`, in the real world, you can separate the REST API access using their own services. First, open and edit `src/app/app.module.ts` then add this import of HttpClientModule that is part of @angular/common/http.

import { HttpClientModule } from '@angular/common/http';

Add it to @NgModule import array after the BrowserModule.

imports: [
  BrowserModule,
  HttpClientModule
],

Back to `src/app/app.component.ts` then add these imports of the required Angular HttpClient, RxJS, and Observable.

import { Observable, of, throwError } from 'rxjs';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { catchError, tap, map } from 'rxjs/operators';

Add these constants before the `@Component`.

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
};
const apiUrl = 'http://localhost:3000/api/v1/products';

Inject `HttpClient` module to the constructor.

constructor(private http: HttpClient) { }

Add the error handler function that returns as an Observable.

private handleError<T> (operation = 'operation', result?: T) {
  return (error: any): Observable<T> => {

    // TODO: send the error to remote logging infrastructure
    console.error(error); // log to console instead

    // Let the app keep running by returning an empty result.
    return of(result as T);
  };
}

Add the functions to get data from the REST API and return the response as Observable. It also, extract or read data using the Pipe method and tap operator and catch the error by calling the error handler. RxJS pipe method is an Observable method to make data reading easier. RxJS Tap operator uses to perform a side effect for every emission on the source Observable but returns an Observable that is identical to the source.

getProducts(): Observable<any[]> {
  return this.http.get<any[]>(apiUrl)
    .pipe(
      tap(product => console.log('fetched products')),
      catchError(this.handleError('getProducts', []))
    );
}

getProduct(id: number): Observable<any> {
  const url = `${apiUrl}/${id}`;
  return this.http.get<any>(url).pipe(
    tap(_ => console.log(`fetched product id=${id}`)),
    catchError(this.handleError<any>(`getProduct id=${id}`))
  );
}

To run that function simply call the subscribe method and put the result to the variable that declared before the constructor.

data: any[] = [];

constructor(private http: HttpClient) {
  this.getProducts()
  .subscribe((res: any) => {
    this.data = res;
    console.log(this.data);
  }, err => {
    console.log(err);
  });
}


Data Exchange between Components

This example shows data exchange between components using service. Data emitted by service that subscribes by components. Component able to change data and data changes received by another component. For that, add a service and two components.

ng g service Shared
ng g component Acomp
ng g component Bcomp

Open and edit `src/app/shared.service.ts` then add this import of RxJS BehaviorSubject. BehaviorSubject is a Subject that requires an initial value and emits its current value to new subscribers.

import { BehaviorSubject } from 'rxjs';

Declare a variable before the constructor that instantiates BehaviorSubject with object data. Also, a variable that converts BehaviorSubject as Observable.

private dataSource = new BehaviorSubject({name: 'Maradona'});
currentData = this.dataSource.asObservable();

Add a function to change the data of BehaviorSubject.

changeData(data: any) {
  this.dataSource.next(data);
}

Next, open and edit `src/app/acomp/acomp.component.ts` then add these imports of Router and SharedService.

import { Router } from '@angular/router';
import { SharedService } from '../shared.service';

Inject that module to the constructor.

constructor(private router: Router, private sharedData: SharedService) { }

Declare a variable before the constructor to hold the received data.

data: any;

Subscribe the observable data from the service inside the NgOnInit function.

ngOnInit() {
  this.sharedData.currentData.subscribe(data => this.data = data);
}

Add a function to change the shared data then emit to its subscriber then navigate to the other component to see the data changes.

changeData() {
  this.sharedData.changeData({name: 'Eric Cantona'});
  this.router.navigate(['/bcomp']);
}

Next, open the `src/app/acomp/acomp.component.html` then replace all HTML tags with these tags.

<p>acomp works!</p>
<p>{{data.name}}</p>
<p>
  <button (click)="changeData()">Send Data</button>
</p>

Do a similar way for the other component, open and edit `src/app/bcomp/bcomp.component.ts` then replace all codes with these.

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { Router } from '@angular/router';
import { SharedService } from '../shared.service';

@Component({
  selector: 'app-bcomp',
  templateUrl: './bcomp.component.html',
  styleUrls: ['./bcomp.component.scss']
})
export class BcompComponent implements OnInit {

  data: any;

  constructor(private router: Router, private sharedData: SharedService) { }

  ngOnInit() {
    this.sharedData.currentData.subscribe(data => this.data = data);
  }

  changeData() {
    this.sharedData.changeData({name: 'Romario Varia'});
    this.router.navigate(['/acomp']);
  }

}

Next, open and edit `src/app/bcomp/bcomp.component.html` then replace all HTML tags with these.

<p>acomp works!</p>
<p>{{data.name}}</p>
<p>
  <button (click)="changeData()">Send Data</button>
</p>


Observable and RxJS in Router

In this example, we will show you how to convert Router events as Observable. RxJS filter() use to look for events of interest and subscribe to them in order to make decisions based on the sequence of events in the navigation process. Still using the previously created components, open and edit `src/app/acomp/acomp.component.ts` then add or modify these imports of @angular/router Router, NavigationStart, RxJS filter, and Observable.

import { Router, NavigationStart } from '@angular/router';
import { filter } from 'rxjs/operators';
import { Observable } from 'rxjs';

Inject the constructor with Router and add to the constructor body the Router events that converted as Observable.

constructor(private router: Router) {
  this.navStart = router.events.pipe(
    filter(evt => evt instanceof NavigationStart)
  ) as Observable<NavigationStart>;
}

Add NavigationStart subscriber to NgOnInit function.

ngOnInit() {
  this.navStart.subscribe(evt => console.log('Navigation Started!'));
}

Next, the example of ActivateRoute that injected router service that makes use of observables to get information about a route path and parameters. Open and edit `src/app/bcomp/bcomp.component.ts` then add/modify these imports of @angular/router ActivatedRoute.

import { ActivatedRoute } from '@angular/router';

Inject above ActivatedRoute to the constructor.

constructor(private activatedRoute: ActivatedRoute) { }

Add ActivatedRoute URL subscribing to the NgOnInit function.

ngOnInit() {
  this.activatedRoute.url
    .subscribe(url => console.log('The URL changed to: ' + url));
}


Observable and RxJS in Reactive Forms

This example will show you how Observable detect the FormControl value changes. The Observable is used by the property in ReactiveForms. For that, we will register the ReactiveForm by open and edit `src/app/app.module.ts` then add/modify this import of ReactiveFormsModule, and FormModule.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

Register the above modules to `@NgModule` imports.

imports: [
  BrowserModule,
  HttpClientModule,
  FormsModule,
  ReactiveFormsModule,
  AppRoutingModule
],

Next, open and edit `src/app/app.component.ts` then add this import of @angular/forms FormGroup and FormControl.

import { FormGroup, FormControl } from '@angular/forms';

Add these variables of FormGroup and log for every FormControl value change.

inputChangeLog: string[] = [];
inputForm: FormGroup;

Add a function that detects the value changes of FormControl then saves to log array variable.

logInputChange() {
  const nameControl = this.inputForm.get('name');
  nameControl.valueChanges.forEach(
    (value: string) => {
      this.inputChangeLog.push(value);
      console.log(this.inputChangeLog);
    }
  );
}

Initialize the FormGroup and call log input changes function inside the NgOnInit function (don't forget to add the OnInit module to this component).

ngOnInit() {
  this.inputForm = new FormGroup({
    name: new FormControl()
  });
  this.logInputChange();
}

Next, open and edit `src/app/app.component.html` then add the FormGroup and InputControl to the main <div>.

<div class="content" role="main">

  <form [formGroup]="inputForm">
    <input type="text" placeholder="Your Name" formControlName="name" />
  </form>

</div>

Now, every FormControl changes will be displayed in the browser console.

That it's for now, it just a few examples of Angular Observable and RxJS. You can get the full source codes from our GitHub.

If you don’t want to waste your time design your own front-end or your budget to spend by hiring a web designer then Angular Templates is the best place to go. So, speed up your front-end web development with premium Angular templates. Choose your template for your front-end project here.

That just the basic. If you need more deep learning about MEAN Stack, Angular, and Node.js, you can take the following cheap course:

Thanks!

Loading…