DEV Community

Bipon Biswas
Bipon Biswas

Posted on

RxJS Of and From in Angular

We will add code directly to the app.component.ts file. We start by importing of and from from the RxJS library import {of, from} from 'rxjs'

Next, we implement the OnInit lifecycle hook and the appropriate import.

then we create ngOnInit method. In ngOnInit, let's create an observable using of and define a set of numbers. Notice that each number is defined as an argument passed to the creation function.

Now what ?

How do we make the observable go?

To start this observable and begin receiving emitted items, we subscribe.

of(2,4, 6, 8).subscribe((item) => console.log(item));
Enter fullscreen mode Exit fullscreen mode

We could pass an observer object into the subscribe with methods for next, error and complete.
But since we only want to implement the next method, we can pass it directly.

The argument to the next method is the emitted item, so we specify that first, then the arrow then the logic we want executed each time the item is emitted. Every time the observable emits the next value, we want to log it, so we'll call console.log.

Of automatically completes, so we don't need to unsubscribe.

Output
Of output
We have created an observable that emits for number and completes.

Now let's try the from create function.

Notice that we defined the numbers in an array and again call subscribe to start this observable and begin receiving emitted items. This time, let's pass in an observer with next, error and complete methods.

The next method provides the emitted item, and we log it.

    from ([20, 15, 10, 5]).subscribe({
      next: (item) => console.log(`resulting item.. ${item}` ),
      error: (err) => console.log(`error occurred ${err}`),
      complete: () => console.log('Completed')
    })
Enter fullscreen mode Exit fullscreen mode

The error method provides the error, and we log that. And complete method has no argument, so we specify empty parentheses and display message.

Notice I'm using the backtick to define TypeScript template strings for string interpolation of the log message.

We see the array elements logged the to the console and the complete message.

from output
We again created an observable that emits four numbers and completes.

app.components.ts file

import { Component, VERSION, OnInit } from '@angular/core';
import {of, from} from 'rxjs'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major;

  ngOnInit(){
    of(2,4, 6, 8).subscribe((item) => console.log(item));
    from ([20, 15, 10, 5]).subscribe({
      next: (item) => console.log(`resulting item.. ${item}` ),
      error: (err) => console.log(`error occoured ${err}`),
      complete: () => console.log('Completed')
    })

of('Apple1', 'Apple2', 'Apple3').subscribe({
  next: (apple) => console.log(`Appled emmitted ${apple}`),
  error: (err) => console.log(`Error occured: ${err}`),
  complete: ()=> console.log('No more apples, go home')
})

  }
}
Enter fullscreen mode Exit fullscreen mode

The subscribe starts the observable, which then emits those string. The observer reacts to those emissions, logging the result.

Summary

Observable

  • Collection of events or values emitted over time

Observer

  • Observes notifications from the Observable
  • Methods to process notification: next(), error(), complete()

Subscriber

  • And Observer that can unsubscribe

Subscription

  • Tells the Observable that the subscriber is ready for notification
  • subscribe() returns a Subscription

Thanks for reading.

Top comments (0)