Rxjs 5:分享不是一个功能

时间:2017-11-10 11:03:53

标签: angular rxjs

更新到RxJs 5后,我收到以下错误:

share is not a function

代码:

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);
    }
}

尝试在http://stackoverflow.com/a/36174340/3955513

之后制作一个globalEvents

RxJs版本:5.5.2

2 个答案:

答案 0 :(得分:2)

这是工作服务。

我已经更新了Thierry Templier的问题作为参考,Plunker

注意import { share } from "rxjs/operators";不是import { share } from "rxjs/operator/share";,如其他地方所述。见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);
  }
}

答案 1 :(得分:1)

您正在导入lettable“share()”运算符,但尝试将其用作原始“补丁”运算符。

您应该按如下方式使用它:

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

...

this.observable = share(temp);

或者像这样:

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

...

this.observable = temp.pipe(share());