At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

,

How To Create Observables In Angular 4

  • By Preetha Ravi
  • August 14, 2018
  • 2165 Views

Hope everyone heard about Observables in Angular but am not sure how many of us know about the types of observables or how to create them in Angular. This blog is aimed to reach you to explain the basics of Observables and also to explain it in a easy way so that you could also create by your own.
So, let’s start with the brief intro about Observables

What Is Observables?

A Observables is used for transferring messages from one component to another component or from component to service or vice versa. Moreover, observables are mainly used for handling multiple values inside the application. You can create observable in any form like an array or object. You can use .next() function for changing the values. Also, you can subscribe the value for getting the value in the place where you needed. It uses event handling for maintaining the data. In order to use observables, angular uses third party libraries called Reactive Extensions(RxJs) so it will always return the latest value. When the value changes then the observable will check for the latest value that is assigned to it. On other case, when you change the value of the observable in any instance, then the value will be automatically changed in other places too.
Asynchronous pipe is an another added concept in observables which will check for the latest value which is emitted. It is mostly used to check changes of the value.
Observable also used in many of the events like the router, reactive forms and so on. So while working on the reactive forms, the values of form control can be used as observable. With help of observables, the form control will change the property of statusChanges and valueChanges to change the event .

Some Significant Methods Of Observables

subscribe() method – To get the value of observable that makes the correspondent change in the value
unsubscribe() method – To stop the notification of the values
next() method – To change the value in the place where it’s necessary.

BehaviorSubject:

Behaviorsubject is also known as subject which used in the concept of observable. The main feature of the behaviorsubject is it will always return a value, so initializing the value in behvaiorsubject is always necessary. Here, we can use behaviorsubject as an observable using the observable() method.

Step1:

First, we want to import the Rxjs library to use the behaviorsubject. Have it on mind that we cannot use the observable without importing the library.
Below code can help you to import Rxjs library,

import { BehaviorSubject } from 'rxjs/BehaviorSubject';

 
Now you will have the Rxjs library installed on your application.

Step2:

First, we want to declare an observable. Since the behaviorsubject will always return a value when we use subscribe method so it’s necessary to declare the value at initial stage itself.
Check the below code to declare an observable in Behaviorsubject

public loggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);

 

Step3:

We want to use the next() method to change the value because we cannot directly change the value in the observables.
So you can try to change the value of observable with below code,

changeLogin(value: boolean) {
this.loggedIn.next(value);
}

 

Related: 4 Must Known Operators In RxJS

 

Step4:

When you want to use the observable, we can subscribe the value from the component where we declared. And in other case if you don’t want to use the observable value, we can use unsubscribe method to unsubscribe the values. However, observables will not use the existing event handler because it will give different event handlers each time you subscribe to it, since I have used observable in the service class i have subscribed the data which you can note on the below code.

this.service. loggedIn.subscribe((val: boolean) => {
this.loggedIn = val;
});

 
Similarly, you could also follow the same steps to other observables also. Here am giving you the quick overview of the other observables too.

Subject :

Such as, Subject is also same like a behavioral subject. The only difference between the subject and the behavior subject is that when you subscribed to value, The old value of the subject variable will not be given in the subscription variable until you set the next value to the subject variable.
Notably, it is used in the case when you don’t want to use the old value and want only the next assigned value to be used. The old subscriptions variables will also be replaced with the new value. The subject can be imported by using the command,

import { Subject } from "rxjs/Subject";
Below is the example for understanding the subject,
import { Subject } from 'rxjs/Subject';
public loggedIn= new Subject();
let subject1, subject2 ;
this.loggedIn.next("string1")
this.loggedIn.subscribe(
data => subject1 = data
)
console.log(subject1,"first console value")
this.loggedIn.next("string2")
console.log(subject1,"second console value")
this.loggedIn.next("string1")
this.loggedIn.subscribe(
data => subject2 = data
)
console.log(subject2,"first console value")
this.loggedIn.next("string 3")
console.log(subject2,"second console value")

 

Result:

Subject

Replay Subject:

In addition, Replay Subject is also same like a subject. However, the only difference between the subject and replay subject is “It holds the array of old values”. Whereas the subject will not contain the old value but here “Replay subject” declaration will be same like “subject”. Above all, once the subscription is done then we need to set the value to “replay subject”. Alongside, we can set how many values needs to be stored by the Replay subject through buffer. Follow the below example,

import { ReplaySubject } from "rxjs/ReplaySubject";
We can define a buffer, i.e., how many old values to be stored is given while declaring itself, follow the syntax of the defining buffer,
const mySubject = new.ReplaySubject(2);
Below is the example for understanding the Replaysubject,
import { ReplaySubject } from 'rxjs/ReplaySubject';
public loggedIn= new ReplaySubject();
let subject1, subject2 ;
this.loggedIn.next("string1")
this.loggedIn.subscribe(
data =>{
subject1 = data
console.log(subject1,"first console value")
}
)
this.loggedIn.next("string2")
this.loggedIn.next("string3")
this.loggedIn.subscribe(
data => {
subject2 = data
console.log(subject2,"second console value")
}
)
this.loggedIn.next("string4")

 

Result:

replaysubject

Asynchronous Subject:

At the end, Asynchronous subject is the last division of the subject. The only thing about asynchronous subject is “It emits only the last value”. It happens only when the subject variable gets completed. Particularly, it is used in the case where you want to use only the final value of the subject variable. You can import the subject by using the command,

import { AsyncSubject } from "rxjs/AsyncSubject";

 
Subject, Replay Subject, Behavior subject, asynchronous subject all come under the concept of observables. Most of the case, they can be used as a service which can be transferred as value from one component to another component.

Never miss out: Angular 6: Upgrading & Summary of New Features

Want to learn more? Then never miss out anything from our blog works, hit the subscribe link , we will send you everything about all the latest technologies & recent updates on web development which could be perfect for your 15 minutes tea break! What else guys? subscribe and go crazy over learning!
If you are looking for angular developers ? Hire Angular developer from Agira Technologies to build best web-apps at affordable rates. Our dedicated Angular developers are well-versed with all the updates and ensure top-notch web applications development to meet your business requirements. For any queries reach us via info@agiratech.com