Reputation: 101456
RxJs, Typescript 1.8 and Angular2.
I have a function which returns an Observable. The Observable calls a web API, which returns a sequence of objects. Here is my actual code:
getClients(): Observable<IClient[]> {
return this.backendService.get(`tracker/clients`)
.map((resp: {}[]) => { return _.map(resp, createClientFromJson)})
.map((clients: IClient[]) => {
this.logger.debug(`Created ${clients.length} Clients from reply`);
return clients;
});
}
The call to backendService.get()
ultimately calls http.get()
, which returns an Observable
.
And my code which consumes the events from the Observable:
loadClients() {
this.getClients().subscribe((clients: IClient[]): void => {
this.clients = this.clients.concat(clients);
this.logger.debug(`Got ${clients.length} clients, now have ${this.clients.length}.`);
})
}
This all works. However my Observable emits a single time - with a sequence of N elements. If the web API returns a sequence of 20 items, only 1 event will be emitted to loadClients()
.
How can I make it so that each item in the sequence is emitted by itself, instead of emitting the entire sequence all at once?
In some parts of my program, I need the entire sequence. In others I need to look for one particular element that matches some criteria.
Upvotes: 0
Views: 798
Reputation: 14375
this.getClients().switch(v => v).subscribe(clients => {
// your original code
});
Upvotes: 2
Reputation: 6335
try this
this.getClients().flatMap(clients => Observable.from(clients)).subscribe(client => {
// do something with client
})
Upvotes: 2