简体   繁体   中英

Angular2 Observables — Replay

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM