Angular2 Observables — Replay

别来无恙 提交于 2019-12-08 15:20:41

问题


I am trying to set up an Angular2 Observable that will replay the latest value.

import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class RefinementService {
    refining: any;
    private r: any;
    constructor() {
        this.refining = new Observable(observer => this.r = observer).replay(1);
    }
}


I continually get errors stating:

Property 'replay' does not exist on type Observable<{}>.

and

this.refining.replay is not a function


Has anyone successfully implemented an observable that will re-emit it's latest value to new subscribers?


回答1:


According to the MIGRATION guide for RxJS5 replay was renamed to publishReplay.

So you should be fine by adding the correct operator

import 'rxjs/add/operator/publishReplay';

// Component
this.refining = new Observable(observer => this.r = observer).publishReplay(1);

You could use ReplaySubject as well.




回答2:


I think you could try to refact your code this way:

import {Injectable} from 'angular2/core';
import {Observable,ReplaySubject} from 'rxjs/Rx';

@Injectable()
export class RefinementService {
  refining: any;
  private r: any;
  constructor() {
    this.refining = new Observable(observer => this.r = observer)
        .subscribe(new ReplaySubject(1));
  }
}

Here is the corresponding plunkr: https://plnkr.co/edit/TrCf8JEGO1toEMqiWg3D?p=preview.

Hope it helps you, Thierry



来源:https://stackoverflow.com/questions/34947642/angular2-observables-replay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!