我想使用一个可观察量来向我的 Angular 应用程序的各个部分发出有关“异常状态”的信号,类似地,但我意识到我并不真正理解它们是如何工作的。
在下面的代码中,我构建了一个观察者对象,并从中创建了一个可观察对象。我想做的是弄清楚如何在 Observable.create 方法的范围之外调用“next”方法,以便我可以将任意事件插入流中。直接在观察者 deos 上调用 next 似乎不是答案。
var observer = {
next: function(value) {
this.myvalue="last value: " + value;
},
error: function(error) {
console.log(error);
},
complete: function() {
console.log('completed');
},
myfunction: function() {
this.myvalue = "Penguins"
},
myvalue: ""
}
let myobs$ : Observable<any> = Observable.create(function(obs) {
obs.next("Some foo");
obs.next("Other foo");
})
let foo=myobs$.subscribe((observer)=> {
console.log("This is the subscription: ", observer)
})
setTimeout(function() {
observer.next("This is a late breaking value");
console.log(observer.myvalue);
}, 2000);
}
此代码产生以下控制台输出:
This is the subscription: Some foo
This is the subscription: Other foo
last value: This is a late breaking value
所以看起来直接在观察者对象上调用 next
(我在底部的超时函数内尝试过)不会在订阅内产生值。
也很清楚,我想我不明白这些东西应该如何工作。如果我设置了一个可观察的对象并且我想“手动”将数据插入到流中以供订阅者获取,那么理解这一点将会很有帮助,那么我到底该怎么做呢?我可以看到你如何通过事件传播的事情(例如鼠标点击或ajax请求)来做到这一点,但我想要做的是创建一个流,当某些有趣的事情发生在不同的地方时,我可以临时提供该流。我的代码。
最佳答案
您应该阅读on RxJs Subject
。这就是你所需要的。
来自文档:
A Subject is a special type of Observable that allows values to be multicasted to many Observers. Subjects are like EventEmitters.
有不同类型的主题。 ReplaySubject
, BehaviorSubject
, AsyncSubject
。我建议您深入研究文档或一些教程,了解如何以及何时使用它们。从您的可观察中,您还希望发出先前的值和新值。您可以使用 the pipable operators that RxJs ships with 进行此类自定义行为。我建议您也阅读这些内容。 Here is another post on stackoverflow这正是你想要的:
基于该示例:
const subject = new Subject().pipe(
startWith('Penguins'), // emitting first value to fill-in the buffer
pairwise(),
map([previous, current] => {
return previous + current;
}),
);
const observer = {
next: (value) => {
console.log(value);
},
error: (error) => {
console.log(error);
},
complete: () => {
console.log('completed');
},
};
// Subjects
const subscriber = subject.subscribe(observer);
subject.next('Some foo');
关于angular - 关于 rxjs observables 的基本问题——如何将数据提供给 observable 'by hand' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60907765/