Reputation: 1192
I'm fetching array of objects from API using angular2 http get method. I would like an observable to return element of the array 1 by 1 with a short delay, how can I achieve this ? That's the code I have now:
return this.authHttp.get('fetch/arrayOfObjects',options).map(res => res.json());
I wan't it to work like the one below, so result is returned by a single element with a 1 second delay:
var obs = Rx.Observable.create(function (observer) {
let dt = [1,2,3,4,5];
for(let e of dt){
setTimeout(() => {
observer.next(e);
}, 1000);
}
});
obs.subscribe(data=> console.log(data));
Upvotes: 0
Views: 2333
Reputation: 96889
You can use concatAll()
and then delay()
to create the pause between each emission (I'm assuming that the remote service returns an array of objects):
return this.authHttp.get('fetch/arrayOfObjects',options)
.map(res => res.json())
.concatAll() // unpack the array into single emissions
.concatMap(val => Observable.of(val).delay(100)) // delay each emission
.subscribe(...)
Upvotes: 5