You are on page 1of 11

4/15/2020 Angular 6 Observables Example Tutorial From Scratch

INVESTMEN

HOME BASICS  BACKEND  FRONTEND 

ABOUT US PRIVACY POLICY CONTACT US

 ANGULAR
FORM
VALIDATI
EXAMPLE
TUTORIA
 ANGULAR
MATERIA
DATEPIC
EXAMPLE
ANGULAR
TUTORIA
 ANGULAR
6 FORMS
TUTORIA Angular 6 Observables
EXAMPLE
FROM Example Tutorial From
SCRATCH
Scratch
 ANGULAR
DEPENDE
 JULY 6, 2018  8 MIN READ
INJECTIO
TUTORIA
EXAMPLE
FROM
SCRATCH IT Project Management Software

ANGULAR Ad Wrike Visit Site



6 EVENT
BINDING
EXAMPLE
TUTORIA
Angular 6 Observables Example
Tutorial  is the today’s leading
 ANGULAR
6 HTTP topic.  Observables are the
GET collections of multiple values over
EXAMPLE time. Observables are lazy.  Angular
 ANGULAR uses observables extensively in the
6 CHARTS
event system and the HTTP service.
EXAMPLE
TUTORIA Observables are very helpful in
FROM asynchronous actions.  If you 
SCRATCH compare observables with
promises, then there is a crucial
di erence as promises always

https://investmentnovel.com/angular-6-observables-example-tutorial-from-scratch/ 1/11
4/15/2020 Angular 6 Observables Example Tutorial From Scratch

 ANGULAR return only one value. Another


6 CRUD thing is that observables are
EXAMPLE
TUTORIA cancelable and promises are not. If
FROM you don’t want your newsletter
SCRATCH anymore, you unsubscribe. You can
 ANGULAR think of observables as newsletters.
COMPON For each subscriber, a new
TUTORIA
newsletter is created. They are then
WITH
EXAMPLE only sent to those people, and not
 ANGULAR to anyone else.
6
LOADING
SPINNER Table of Contents 
EXAMPLE 1. #Push vs. Pull in Observables
2. #Creating an observable
 ANGULAR 3. Angular 6 Observables Example Tutorial
6 4. #1: Install Angular 6.
ROUTING 5. #2: Create a JSON server.
EXAMPLE 6. #3: Fetch the data.
Protect you
online
 C #PUSH VS. PULL IN accounts f
digital thre
 ANGULAR
OBSERVABLES
 VUE.JS
In Push, The data producer decides
 BOOTSTRA
when the consumer ( subscriber to
 LARAVEL the newsletter) gets the data.  The Learn Mo
 NODE.JS
promises are the most common
way to push in JavaScript today. A
 MONGODB
promise (the producer) delivers a
resolved value to registered
callbacks.

Protect you
from webcam
spies at all
times.

Learn More

https://investmentnovel.com/angular-6-observables-example-tutorial-from-scratch/ 2/11
4/15/2020 Angular 6 Observables Example Tutorial From Scratch

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.
Protecting
your ident
import { Observable } from 'rxjs';

online.
// create observable
const simpleObservable = new Observab
// observable execution
observer.next('Hello Observable')
observer.complete();
});
Learn Mo

// subscribe to the observable


simpleObservable.subscribe();

As you can see in the example  Search the site


observables are  created  by using
the new Observable() call,
FIND US ON
then  subscribed  to by an
FACEBOOK
observer,  executed  by calling
the next().

ANGULAR 6 CATEGORIES
OBSERVABLES
EXAMPLE TUTORIAL ANGULAR 
We will create a JSON server and BOOTSTRAP
serve the data. We handle that data
C

https://investmentnovel.com/angular-6-observables-example-tutorial-from-scratch/ 3/11
4/15/2020 Angular 6 Observables Example Tutorial From Scratch

using Observables. So as always, we LARAVEL


start our project by installing
Angular 6 using the following MONGODB

command.
NODE.JS

VUE.JS

FOLLOW US
Protect you
from webcam
spies at all
   
times.

Learn More

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

https://investmentnovel.com/angular-6-observables-example-tutorial-from-scratch/ 4/11
4/15/2020 Angular 6 Observables Example Tutorial From Scratch

Start Download - PDF Now


FromDocToPDF

Convert Any File to a PDF. Get the Free From Doc to Pdf
App!

OPEN

Create a fake data using this


package called json-server.

Inside the project root, create one


le 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" 
}]
}

https://investmentnovel.com/angular-6-observables-example-tutorial-from-scratch/ 5/11
4/15/2020 Angular 6 Observables Example Tutorial From Scratch

Now, start the JSON server using


the following command.

#3: FETCH THE DATA.


Now, inside  app  folder, create one
le 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 le by typing the


following command.

ng g s user --spec=false

Write the following code inside a


user.service.ts  le. It will fetch the
data from the json server.

// user.service.ts

import { Injectable } from '@angular/


import { HttpClient } from '@angular/ 
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

@Injectable({

https://investmentnovel.com/angular-6-observables-example-tutorial-from-scratch/ 6/11
4/15/2020 Angular 6 Observables Example Tutorial From Scratch

providedIn: 'root'
})
export class UserService {

constructor(private http: HttpClien

protected url = 'http://localhost:4

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  le looks


like this.

// app.component.ts

import { Component, OnInit } from '@a


import { UserService } from './user.s
import { IUser } from './IUser';
import { Observable } from 'rxjs';

@Component({
selector: 'app-root',
templateUrl: './app.component.html'
styleUrls: ['./app.component.css']
})
export class AppComponent implements

protected title = 'app';


protected users$: Observable<IUser[

constructor(public userservice: Use 


ngOnInit() {
this.userservice.getUsers().subsc
this.users$ = res;

https://investmentnovel.com/angular-6-observables-example-tutorial-from-scratch/ 7/11
4/15/2020 Angular 6 Observables Example Tutorial From Scratch

});
}
}

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

https://investmentnovel.com/angular-6-observables-example-tutorial-from-scratch/ 8/11
4/15/2020 Angular 6 Observables Example Tutorial From Scratch

Tweet

Save

ANGULAR 6

RELATED POSTS

ANGUL ANGULAR

Angul Angular
6 6
Http Routing

ADMIN ADMIN

POST YOUR THOUGHTS

COMMENT TEXT*

Name*

Email*

Website

Save my name, email, and website in


this browser for the next time I comment.

SEND

This site uses Akismet to reduce spam.


Learn how your comment data is processed.

3 COMMENTS

https://investmentnovel.com/angular-6-observables-example-tutorial-from-scratch/ 9/11
4/15/2020 Angular 6 Observables Example Tutorial From Scratch

DIMA 
Avatar
the `users$` object in your
example is not an observable.
It’s an actual object.

DANIEL LIVERANT 
Avatar
There’s a small mistake in
your code.
users$ in not an observable.
the “res” object inside your
subscribe function is the data.
if you wrote something like
this:
this.users$ =
this.userservice.getUsers();
then users$ would be an
observable and you can write
in your HTML something
like:

instead I would suggest this


sample of code:

JS: (add “users” property)


NgOnInit:
this.users$ =
this.userservice.getUsers().sub
=> {
this.users = res;
});

NgOnDestroy:
this.users$.unsubscribe();

HTML:

Avatar
JOHN JOSEPH MIKALAUSKAS 

I nEeded to import httpclientmodule in the


app.module.ts le for angular 8

https://investmentnovel.com/angular-6-observables-example-tutorial-from-scratch/ 10/11
4/15/2020 Angular 6 Observables Example Tutorial From Scratch

Copyright 2020 ©  InvestmentNovel.  All rights reserved  

https://investmentnovel.com/angular-6-observables-example-tutorial-from-scratch/ 11/11

You might also like