How to Convert Array to Observable in Angular

To convert an Array to an Observable in Angular, you can use the from() method provided by RxJS.

Here’s how you can convert an array to an observable:

Step 1: Import the necessary items from the RxJS library

import { from } from 'rxjs';

Step 2: Convert the array to an observable

import { from } from 'rxjs';

const mainArr = [1, 2, 3, 4, 5];

const mainObservable = from(mainArr);

mainObservable.subscribe({
  next: (v) => console.log(v),
  error: (e) => console.error(e),
  complete: () => console.info('complete')
});

Output

Convert the array to an observable

Here’s a breakdown:

  1. next: This function handles each emitted value from the observable. In your code, for every value v emitted by mainObservable, console.log(v) will be executed.
  2. error: This function handles any error that might occur during the execution of the observable. If an error occurs, the console.error(e) will be executed.
  3. complete: This function gets called once the observable completes (i.e. when it emits no more values). Once mainObservable completes, console.info(‘complete’) will be executed in your code.

Using an observer object like this can make your code more readable, especially when the logic within each callback function becomes more involved.

Related posts

Convert Promise to Observable