RXJS获取ReplaySubject的当前值

时间:2017-10-15 00:17:44

标签: angular rxjs behaviorsubject

我试图在登录时从ReplySubject中提取当前值。在当前流中的订阅时,返回先前的值而不是当前值。收到的东西是登录时的前一个东西,而不是当前的东西。有没有办法在ReplaySubject中获取订阅时observable的当前值而不必求助于BehaviorSubject?

stuff.service.ts:

 private _stuffSubject = new ReplaySubject<any>();
 private _stuff$: Observable<any> = this._someSubject.asObservable();

  get stuff$ () {
   return this._stuff$;
  }

  private fetchStuff () {
    return this.http.get('/stuff/current')
      .map(data =>  {
        return data.json()
      })
      .catch(err => {
        console.debug(this.constructor.name, 'handled error ->', err.message);
        return Observable.of(false);
      })
      .map(stuff => {
        this._stuffSubject.next(stuff);
      })
  }

stuff.component.ts:

this.stuffService.stuff$
  .subscribe(({stuff1, stuff2, stuff3}) => {
    this.stuff1 = `${stuff1}`;
    this.stuff2 = `${stuff2}`;
    this.stuff3 = `${stuff3}`;
  });

1 个答案:

答案 0 :(得分:2)

您可以将缓冲区大小设置为1:

private _stuffSubject = new ReplaySubject<any>(1);