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 delay in angular and typescript.
Observable
are objects in RXJS for asynchronous operations Angular application.
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 the 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 is an angular code displays 3 seconds for 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 console with a delay of 3 seconds Output:
start
end
test
test2
test3
🧮 Tags
Recent posts
Multiple ways to iterate a loop with index and element in array in swift How to reload a page/component in Angular? How to populate enum object data in a dropdown in angular| Angular material dropdown example How to get the current date and time in local and UTC in Rust example Angular 13 UpperCase pipe tutorial | How to Convert a String to Uppercase exampleRelated posts