1
votes

From angular2

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes.

For my case, if I want the async to subscribe to the events generated from XMLHttpRequest call's xhr.upload.onprogress. Shall I create a Subject or Observable? Every time when the event comes, I need to push it to all subscribers(including the async pipe) of this (Subject or Observable)

  xhr.upload.onprogress = (event) => {
    this._progress = Math.round(event.loaded / event.total * 100);
    this._subject.onNext(this._progress/100); // push the progress value to the async pipe who is the subscriber
  };
1

1 Answers

2
votes

You can use either but there is a bit more work to do with raw observable since you need to set the observer and make the observable hot. Then you can use the observer to notify.

observer$:Observer<number>;

observable:Observable<number> = Observable.create(observer => {
  this.observer$ = observer;
}).share();

xhr.upload.onprogress = (event) => {
  this._progress = Math.round(event.loaded / event.total * 100);
  this.observer$.next(this._progress/100);
};

With subject, it's already the case (hot and combine observable / observer). Note that you should use next instead of onNext:

xhr.upload.onprogress = (event) => {
  this._progress = Math.round(event.loaded / event.total * 100);
  this._subject.next(this._progress/100);
};