How can I append items to Observable

2020-02-10 11:22发布

问题:

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?

回答1:

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.”


回答2:

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.



回答3:

Take a look at BehaviorSubject:

It's an Observable where you can push a new item as containing object.



标签: angular rxjs