Angular 6 Observables Example Tutorial is the today’s leading topic. Observables are the collections of multiple values over time. Observables are lazy. Angular uses observables extensively in the event system and the HTTP service. Observables are very helpful in asynchronous actions. If you compare observables with promises, then there is a crucial difference as promises always return only one value. Another thing is that observables are cancelable and promises are not. If you don’t want your newsletter anymore, you unsubscribe. You can think of observables as newsletters. For each subscriber, a new newsletter is created. They are then only sent to those people, and not to anyone else.

#Push vs. Pull in Observables

In Push, The data producer decides when the consumer ( subscriber to the newsletter) gets the data. The promises are the most common way to push in JavaScript today. A promise (the producer) delivers a resolved value to registered callbacks.

In Pull, the data consumer decides when it get’s data from the data producer. The producer is unaware of when data will be delivered to the consumer. Javascript function uses the pull pattern. The function is a Producer of the data, and code that calls a function is consuming it by “pulling” out a return value from its call.

#Creating an observable

You can create the simple observable in Angular like the following code.

import { Observable } from 'rxjs'; // create observable const simpleObservable = new Observable((observer) => { // observable execution observer.next('Hello Observable'); observer.complete(); }); // subscribe to the observable simpleObservable.subscribe();

As you can see in the example observables are created by using the new Observable() call, then subscribed to by an observer, executed by calling the next().

Angular 6 Observables Example Tutorial

We will create a JSON server and serve the data. We handle that data using Observables. So as always, we start our project by installing Angular 6 using the following command.

#1: Install Angular 6.

If you have not installed Angular CLI previously, then install it using the following command.

npm install -g @angular/cli # or yarn add global @angular/cli

Now, create a local project using the following command.

ng new observables

#2: Create a JSON server.

Create a fake data using this package called json-server.

Inside the project root, create one file called data.json and add the following code.

{ "results": [ { "id": "1", "name": "RDJ", "movies": "100" }, { "id": "2", "name": "Tom Holland", "movies": "3" }, { "id": "3", "name": "Benedict Cumberbatch", "movies": "10" }, { "id": "4", "name": "Chris Hemsworth", "movies": "30" }, { "id": "5", "name": "Chris Evans", "movies": "20" }] }

Now, start the JSON server using the following command.

#3: Fetch the data.

Now, inside app folder, create one file called IUser.ts. It is an interface that contains the property with its datatype we expect from the server.

// IUser.ys export interface IUser { id: Number; name: String; movies: Number; }

Create a service file by typing the following command.

ng g s user --spec=false

Write the following code inside a user.service.ts file. It will fetch the data from the json server.

// user.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map } from 'rxjs/operators'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class UserService { constructor(private http: HttpClient) { } protected url = 'http://localhost:4000'; getUsers(): Observable<any> { return this .http .get(`${this.url}/results`) .pipe( map(res => res) ); } }

Now, here, we have used Observables. The getUsers() function will return an observable and that observable is then handled by the calling function.

So, our app.component.ts file looks like this.

// app.component.ts import { Component, OnInit } from '@angular/core'; import { UserService } from './user.service'; import { IUser } from './IUser'; import { Observable } from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { protected title = 'app'; protected users$: Observable<IUser[]>; constructor(public userservice: UserService) {} ngOnInit() { this.userservice.getUsers().subscribe(res => { this.users$ = res; }); } }

Here, we have subscribed the observable and then attach the response to the users$ observable. We are using $ sign in a variable because generally it is a best practice to use a dollar sign in that describes the Observable. Finally, our HTML file looks like this.

<table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Movies</th> </tr> </thead> <tbody> <tr *ngFor="let user of users$"> <td>{{ user.id }}</td> <td>{{ user.name }}</td> <td>{{ user.movies }}</td> </tr> </tbody> </table>

And our output looks like below.

Finally, Angular 6 Observables Example Tutorial From Scratch is over.