Multiple ways to Create an Observable with Delay| Angular examples

This tutorial shows an example of creating an observable with a delay in angular and typescript.

Observable are objects in RXJS for asynchronous operations in Angular applications.

We already have a how to create an obeservable array in Angular

How to create an observable with delay in Angular?

-Create an array of type strings and initialized them with string values.

  • Create an array of an observable array using () from rxjs. And pipe is used to attach delay operation with 4000 milliseconds.
  private myarray: string[] = ["test", "test2", "test3"]
  array1: Observable<string[]> = of(this.myarray).pipe(delay(4000));

Here is an angular complete code

import { Component } from '@angular/core';
import { delay, from, Observable, of, take, tap } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  private myarray: string[] = ["test", "test2", "test3"]
  array1: Observable<string[]> = of(this.myarray).pipe(delay(5000));

  private result: string[] = [];
  constructor() {
    console.log("start")
    this.array1.subscribe(item => console.log(item));
    console.log("end")
  }

}

You would see the console log as follows and prints the array after 4 seconds.

start;
end[("test", "test2", "test3")];

Suppose you want to delay with a timer for every array element.

concatMap is used to map with again observable string with a delay of 3 seconds

  private myarray: string[] = ["test", "test2", "test3"]
  strings$: Observable<string[]> = of(this.myarray);
  result: Observable<string> = from(this.myarray).pipe(concatMap(item => of(item).pipe(delay(3000))));

Here are an angular code displays 3 seconds for the array element

import { Component } from '@angular/core';
import { concatMap, delay, from, Observable, of, take, tap } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  private myarray: string[] = ["test", "test2", "test3"]
  strings$: Observable<string[]> = of(this.myarray);
  result: Observable<string> = from(this.myarray).pipe(concatMap(item => of(item).pipe(delay(3000))));

  constructor() {
    console.log("start")
    this.result.subscribe(item => console.log(item));
    console.log("end")
  }

}

Each array element is printed to the console with a delay of 3 seconds Output:

start;
end;
test;
test2;
test3;