THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
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
-Create an array of type strings and initialized them with string values.
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
🧮 Tags
Recent posts
Puppeteer Login Test example How to convert Double to Integer or Integer to double in Dart| Flutter By Example Best ways to fix 504 gateway time out in nodejs Applications Fix for Error No configuration provided for scss Multiple ways to List containers in a Docker with examplesRelated posts