Create Observable From String, Array And Object In Angular

Create Observable From String, Array And Object In Angular

In this article, we will learn how to make an observable in Angular using the create, of, and from operators. They can be used to make new observables out of an array, string, object, collection, or any other static data. Also, understand the distinction between the Of and From operators. If you're unfamiliar with observables, we recommend starting with the Angular observable.

Observable creation functions

In Angular, there are a variety of ways to make an observable. As taught in the observable lesson, you can use Observable Constructor. There are several functions that can be used to create new observables. These operators allow us to generate observables from arrays, strings, promises, iterables, and other data types. Some of the operators are listed below.

  • create
  • defer
  • empty
  • from
  • fromEvent
  • interval
  • of
  • range
  • throw
  • timer

The RxJs core library includes all creation-related operations. It's available in the 'rxjs' library.

Create

The Create method is one of the most straightforward. Behind the scenes, the create method calls the observable constructor. You don't need to import Create because it's a method of the observable object.

ngOnInit() {
 
   //Observable from Create Method
   const obsUsingCreate = Observable.create( observer => {
     observer.next( '1' )
     observer.next( '2' )
     observer.next( '3' )
 
     observer.complete()
   })
   
    obsUsingCreate
      .subscribe(val => console.log(val),
              error=> console.log("error"),
              () => console.log("complete"))
}
 
 
 
****Output *****
1
2
3
Complete

Observable Constructor

This was covered in the previous tutorial. The Observable. create method and the observable constructor are identical. The constructor is called behind the scenes by the Create method.

ngOnInit() {
   //Observable Using Constructor
   const obsUsingConstructor = new Observable( observer => {
      observer.next( '1' )
      observer.next( '2' )
      observer.next( '3' )
 
      observer.complete()
   })
 
   obsUsingConstructor
        .subscribe(val => console.log(val),
                error=> console.log("error"),
                () => console.log("complete"))
}
 
 
****Output *****
1
2
3
complete

Of Operator

The Of constructs the observable from the arguments you provide. You can give Of any number of arguments. Each argument was sent out one at a time, one after the other. In the end, it sends the Complete signal.

You must import it from the rxjs library to use it, as seen below.

import { of } from 'rxjs';

observable from an array

An array is an example of what can be sent. It's worth noting that the complete array is sent out at once.

ngOnInit() {
  const array=[1,2,3,4,5,6,7]
  const obsof1=of(array);
  obsof1.subscribe(val => console.log(val),
           error=> console.log("error"),
          () => console.log("complete"))
 
}
 
 
**** Output ***
[1, 2, 3, 4, 5, 6, 7]
complete

More than one array can be sent.

ngOnInit() {
  const array1=[1,2,3,4,5,6,7]
  const array2=['a','b','c','d','e','f','g']  
  const obsof2=of(array1,array2 );
  obsof2.subscribe(val => console.log(val),
           error=> console.log("error"),
          () => console.log("complete"))
 
}
 
 
**** Output ***
[1, 2, 3, 4, 5, 6, 7]
['a','b','c','d','e','f','g']
complete

observable from a sequence of numbers

In the example below, we send 1,2, and 3 as arguments to the from function. Each was released on its own.

ngOnInit() {
    const obsof3 = of(1, 2, 3);
    obsof3.subscribe(val => console.log(val),
      error => console.log("error"),
      () => console.log("complete"))
 
}
 
 
 
**** Output ***
1
2
3
complete

observable from string

The method receives two strings. Each argument is broadcast in its entirety.

ngOnInit() {
    const obsof4 = of('Hello', 'World');
    obsof4.subscribe(val => console.log(val),
      error => console.log("error"),
      () => console.log("complete"))
}
 
 
**** Output ***
Hello
World
complete

observable from a value, array & string

To the Of operator, we can pass anything. It simply emits them one after another.

ngOnInit() { 
    const obsof5 = of(100, [1, 2, 3, 4, 5, 6, 7],"Hello World");
    obsof5.subscribe(val => console.log(val),
      error => console.log("error"),
      () => console.log("complete"))
}
 
**** Output ***
100
[1, 2, 3, 4, 5, 6, 7]
Hello World
complete

From Operator

The From Operator takes only one iterable input and converts it to an observable.

It can be used to convert.
  1. an Array,
  2. anything that behaves like an array
  3. Promise
  4. any iterable object
  5. collections
  6. any observable object

It can iterate nearly anything and transform it into an Observable.

You must import it from the rxjs library to using it, as seen below.

import { from } from 'rxjs';

observable from an array

The example below shows how to make an array into an observable. It's worth noting that each array element is iterated and emitted independently.

ngOnInit() {
 
    const array3 = [1, 2, 3, 4, 5, 6, 7]
    const obsfrom1 = from(array3);
    obsfrom1.subscribe(val => console.log(val),
      error => console.log("error"),
      () => console.log("complete"))
 
}
 
*** Output ****
1
2
3
4
5
6
7
complete

Observable from string

The form operator loops through the string, emitting each character. The following is an example.

ngOnInit() { 
  const obsfrom2 = from('Hello World');
    obsfrom2.subscribe(val => console.log(val),
      error => console.log("error"),
      () => console.log("complete"))
}
 
 
*** Output ****
H
e
l
l
o
 
W
o
r
l
d
complete

Observable from collection

It is possible to convert anything that can be iterated into an observable. Here's an example of how to use a collection.

ngOnInit() {
      let myMap = new Map()
      myMap.set(0, 'Hello')
      myMap.set(1, 'World')
      const obsFrom3 = from(myMap);
      obsFrom3.subscribe(val => console.log(val),
        error => console.log("error"),
        () => console.log("complete"))
)
 
*** output ***
[0, "Hello"]
[1, "World"]
complete

Observable from iterable

The operator can be used to turn any Iterable type, such as Generator functions, into an observable.

ngOnInit() {
     const obsFrom4 = from(this.generateNos())
      obsFrom4.subscribe(val => console.log(val),
      error => console.log("error"),
      () => console.log("complete"))
}
 
*generateNos() {
   var i = 0;
   while (i < 5) {
     i = i + 1;
     yield i;
  }
 
 
*** Output ***
1
2
3
4
5

Observable from promise

It can be used to turn a Promise into an observable.

ngOnInit() {
    const promiseSource = from(new Promise(resolve => resolve('Hello World!')));
    const obsFrom5 = from(promiseSource);
    obsFrom5.subscribe(val => console.log(val),
      error => console.log("error"),
      () => console.log("complete"))
}
 
*** Output ****
Hello World
complete

Of Vs From

Offrom
Accepts variable no of argumentsAccepts only one argument
emits each argument as it is without changing anythingiterates over the argument and emits each value

Conclusion

To build a new observable, we can use the Create method or the Observable Constructor. When you have array-like values, you may use the Of operators to construct an observable by passing them as a distinct parameter to the Of method. The From Operate seeks to iterate over everything that has been supplied to it and builds an observable from it. In the RxJS package, there are numerous more operators or methods for creating and manipulating the Angular Observable. In the next tutorials, we'll go through a number of them.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post