Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 680
JRulle Avatar asked Jan 22 '16 13:01

JRulle


2 Answers

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

like image 84
Thierry Templier Avatar answered Oct 15 '22 21:10

Thierry Templier


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.

like image 24
Eric Martinez Avatar answered Oct 15 '22 19:10

Eric Martinez