Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rxjs 5: share is not a function

Tags:

angular

rxjs

After updating to RxJs 5 I am getting the following error:

share is not a function

Code:

import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import { Injectable } from '@angular/core';
import { share } from "rxjs/operators/share";
import * as m from '../../models/app.models';

@Injectable()
export class SharedService {
    observable: Observable<any>;
    observer: Observer<any>;

    constructor() {
        var temp = Observable.create((observer: Observer<any>) => {
            this.observer = observer;
        });
        this.observable = temp.share(); <- Error here
    }

    broadcast(event: m.SharedEventModel) {
        this.observer.next(event);
    }

    on(eventName, callback) {
        return this.observable.filter((event) => {
            return event.Name === eventName;
        }).subscribe(callback);
    }
}

Trying to make a globalEvents following http://stackoverflow.com/a/36174340/3955513

RxJs Version: 5.5.2

like image 794
Shyamal Parikh Avatar asked Jan 29 '23 06:01

Shyamal Parikh


2 Answers

This is the working service.

I've updated Thierry Templier's plunker from the question you're using as a reference, Plunker

Note, import { share } from "rxjs/operators"; not import { share } from "rxjs/operator/share"; as stated elsewhere. See lettable-operators.md

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import { share } from "rxjs/operators";   // lettable operator, tree-shakeable
import { filter } from "rxjs/operators";

@Injectable()
export class SharedService {
  observable: Observable<any>;
  observer: Observer<any>;

  constructor() {
    var temp = Observable.create((observer: Observer<any>) => {
      this.observer = observer;
    });
    this.observable = temp.pipe(share());
  }

  broadcast(event) {
    this.observer.next(event);
  }

  on(eventName, callback) {
    this.observable.pipe(filter(x => x.name === eventName))
      .subscribe(callback);
  }
}
like image 83
Richard Matsen Avatar answered Feb 12 '23 22:02

Richard Matsen


You're importing lettable "share()" operator but trying to use it as the original "patch" operators.

You should use it as follows:

import { share } from "rxjs/operator/share";

...

this.observable = share(temp);

Or like this:

import { share } from "rxjs/operators/share";

...

this.observable = temp.pipe(share());
like image 24
martin Avatar answered Feb 13 '23 00:02

martin