RxJS-如何将新道具传递给观察者

时间:2018-11-07 20:38:55

标签: node.js rxjs observable

使用RxJS如何在观察者上传递新属性?所以基本上,我希望道具“ customProp”可用于观察

const { Observable } = require('rxjs');

const observable = Observable.create(function (observer) {
    console.log(observer.customProp); //How to get this working?
    observer.next(1);
    observer.next(2);
    observer.next(3);
    setTimeout(() => {
        observer.next(4);
        observer.complete();
    }, 1000);
});

console.log('just before subscribe');
observable.subscribe({
    next: x => console.log('got value ' + x),
    error: err => console.error('something wrong occurred: ' + err),
    complete: () => console.log('done'),
    customProp: 'Hello World RxJS',
});
console.log('just after subscribe');

---->>> Output
just before subscribe
undefined //How can I get this working, please?
got value 1
got value 2
got value 3
just after subscribe
=> undefined
got value 4
done

添加更多信息-所以基本上我正在尝试创建一个冷可观察的场景,其中制作人需要一个应该来自订阅者的道具

//Cold observable
var coldObservable = new Observable((observer) => {
    var myProducerObj = new MyProducer();
    myProducerObj.executeQuery(observer.customProp);
   // How could we get customProp over here?
});

添加使用信息- coldObservable是数据库连接功能,而customProp是需要在数据库上执行的查询

1 个答案:

答案 0 :(得分:1)

不扩展Observable类是不可能的,并且不需要这样做。可能是工厂功能:

const createObservableWithCustomProp = (customProp, observer) => {
  return new Observable((observer) => {
    var myProducerObj = new MyProducer(customProp);
    ...
  });
};

通常,几乎不需要手动构建可观察对象,因为RxJS API提供了丰富的功能集来创建,转换和组合可观察对象。