首页 文章

异步管道从Observable或Subject获取值?

提问于
浏览
1

来自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.

对于我的情况,如果我希望async订阅从XMLHttpRequest调用xhr.upload.onprogress生成的事件 . 我要创建一个Subject或Observable吗?每次事件发生时,我都需要将它推送给所有订户(包括异步管道)(Subject或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 回答

  • 2

    你可以使用其中任何一个,但是对于原始的observable还有一些工作要做,因为你需要设置观察者并使可观察的热点 . 然后你可以使用观察者来通知 .

    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);
    };
    

    对于主题,它已经是这种情况(热和可观察/观察者结合) . 请注意,您应该使用 next 而不是 onNext

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

相关问题