Prerequisites
- Basic knowledge of Angular
- Setup of a local development environment. You will need Angular CLI to set up your environment.
Introduction
In this article we will be learning about using Observable in Angular.
Angular Observable
An observable is a function that converts an ordinary stream of data into one which act as a wrapper around ordinary streams of data. Observable Are lazy: they’re not executed until we subscribe to them using the subscribe() method. Observable is sequence of data that is emitted over period of time which can be any type-string,events etc. While fetching the data through the observables we need to subscribe those observables and then need to write the repective logic to process the data which we fetch using the observables in the subscribe method.
We need an observer in order to listen to and track the changes of observables which have methods like like – next (), error (), complete().Observables are useless until we subscribe to it To work with observables you need to import RxJS library in your Angular code.
Angular use observables very frequently in most async operations
- HTTP
- Routing
- Event Handling
Usage
In Angular, Observable instances are used to specify subscriber functions. Any time a consumer wants to execute the function, the subscribe() method is called. The subscribe() method provides a way to retrieve messages and values to be published.
Create Angular Project
Let’s create new angular project to play around with using Observables in Angular.
We will create simple todo list to play around with Observables in Angular.
Open the terminal and run the folllowing commad:
ng new observable-example
Now An Angular routing window will appear asking if you wish to use Angular routing. Click “(Y/N)”. As this tutorial will now cover routing, let’s skip it by typing and followed by enter.
Following that, a new prompt will appear for selecting the CSS format.
Select “CSS” as the default option and press enter.
It will take some time for the project to create all the necessary files and packages. The project will be created once you receive a message stating: “Packages have been successfully installed.”.
Now enter following command in the terminal.
cd observable-example
ng serve
As soon as the compilation is complete, the application will launch in a new browser.
Check the URL in the browser at http://localhost:4200
RxJS
Observable is a class within the RxJS library. . RxJS operators use Observables as a basic building block for reactive programming. RxJS library provides operators such as subscribe, map, mergeMap, switchMap, exhaustMap, debounceTime, of, retry, catchError, throwError, etc. In order to use RxJS library in Angular programming, we need to ensure that we have installed RxJS.
Install rxjs package if not installed in our application
npm install rxjs --save
Create a service and model files.
In the terminal, enter the following command.
ng g s services/todo
It will add a todo service tile to the app/services directory.
Let’s create a models directory within the app/model directory and create the todo.model.ts file with the following code.
// todo.model.ts
export class Todo {
id: Number;
title: String
}
We have defined the Todo type in our Application,id and title are propertiesIn our Application, we defined the type ToDo, and we have assigned properties to it: ID and title
The next step is to add the demo data to the todo.service.ts file.
import { Injectable } from '@angular/core';
import { Todo } from '../models/todo.model';
@Injectable({
providedIn: 'root'
})
export class TodoService {
todo: Todo[] = [{
'id': 1,
'title': 'Have a meeting'
}, {
'id': 2,
'title': 'Plain daily task'
}]
constructor() { }
}
Create an observable
Now we will create a new function called getTodoList from where we will return the data in the form of an observable.We can subscribe to it, collect the data, and display it on the frontend.
To use Observable
in our Angular application, we need to import it as following.
import { Observable } from 'rxjs';
Let’s add getTodoList function in TodoService file.
import { Injectable } from '@angular/core';
import { Todo } from '../models/todo.model';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class TodoService {
todo: Todo[] = [{
'id': 1,
'title': 'Have a meeting'
}, {
'id': 2,
'title': 'Plain daily task'
}]
constructor() { }
public getTodoList(): any {
const todoObservable = new Observable(observer => {
setTimeout(() => {
observer.next(this.todo);
}, 1000);
});
return todoObservable;
}
}
Here , we have imported Observable from rxjs and defined a single function that returns an Observable. The observable object is passed one argument with a timeout function. After 1 second, if the subscriber subscribes the observable, it will produce the entire array of todos.
Using Subscriber
The observable type has a subscribe()
method that accepts an observer as a parameter.
The subscribe()
method begins sending values to the supplied observer object by executing the observable object’s subscriber function.
Now,We need to subscribe the observable and get the todos data in app.component.ts file.
Add code below in app.component.ts file
import { Component, OnInit } from '@angular/core';
import {Todo} from './models/todo.model';
import {TodoService} from './services/todo.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = "Observable Demo";
todos:Todo[]=[];
constructor(private todoService:TodoService){}
ngOnInit(): void {
const todoObservable = this.todoService.getTodoList();
todoObservable.subscribe((todo: Todo[]) => {
this.todos = todo;
console.log('todos',this.todos);
});
}
}
Display the Data
Replace the code in app.component.html page inside div with content class by the code below.
<div class="container">
<div class="row">
<div class="col-md-12" *ngFor="let todo of todos">
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ todo.id }} {{ todo.title }}</h5>
</div>
</div>
</div>
</div>
</div>
We can data displayed at http://localhost:4200
Conclusion
We have learned how to use observable in Angular and how to retrieve data from observables using subscribers in this article.
For more details,Please check the official Angular Observable Documentation and source code in Github