How do I append items to Observable
?
This is some code:
this.logEntries = this.controllerService.getLog(this.controller.remoteID, this.skip, this.max);
this.logEntries.subscribe(a => {
this.allLogEntries.add(this.logEntries)
});
and here is their declarations:
logEntries: Observable<Log[]>;
allLogEntries: Observable<Log[]> = Observable.empty<Log[]>();
I want to append items to allLogEntries as they are being fetched from the web service. How do I do this?
Perhaps the scan
operator could interest you. Here is a sample:
obs.startWith([])
.scan((acc,value) => acc.concat(value))
.subscribe((data) => {
console.log(data);
});
See this question for more details:
- Angular 2 Updating objects in “real time.”
If you want to join two observables together, you need to e.g. combineLatest
:
Observable
.combineLatest(this.logEntries, this.allLogEntries)
.subscribe(...);
This gives you access to the latest values from each observable, updated as either of them change, and you can combine them as needed.
If you want to be able to manually push entries into one of the source observables, make it a Subject
:
this.logEntries = new Subject();
Observable
.combineLatest(this.logEntries, this.allLogEntries)
.subscribe(...);
then you can invoke an update with:
this.logEntries.next(...);
and your subscription will receive the new logEntries
along with the most recent allLogEntries
. Depending on the behaviour you want, you can use a ReplaySubject
or BehaviourSubject
instead of the vanilla Subject
.
Take a look at BehaviorSubject:
It's an Observable
where you can push a new item as containing object.