使用Observable检测变量的变化 [英] Using an Observable to detect a change in a variable
问题描述
我想我误解了Observables应该如何使用。我想要输入一个值,当值更改时,它应该发出新值。我认为这就是它们的用途,但是所有教程和文档似乎都没有这样做,但与此同时,我总是看到它们以这种方式应用。例如,当您订阅FirebaseListObservable时,以角度为单位,当firebase中的值更改时,它将触发订阅中的快照。我想为我自己的变量做这个。假设我只有一个字符串变量,当它发生变化时,会触发任何订阅。
I think I misunderstand how Observables are supposed to be used. I want to put a value in, and when the value changes it should emit the new value. I thought that was what they were for, but all the tutorials and docs don't seem to do this, but at the same time, I always see them being applied this way. For example, in angular when you subscribe to a "FirebaseListObservable", when the value in firebase changes it fires off a snapshot in the subscription. I want to make that for my own variable. Let's say I just have a string variable, and when it changes, it fires off any subscriptions.
推荐答案
通常我会拥有在组件中订阅的服务中的可观察对象,但为了方便这个答案,我将它们全部捆绑在一个类中。我列出了解释每一步的评论。我希望这有帮助。 :)
Normally I would have my observables in services that get subscribed to in components, but I bundled them all in one class for the convenience of this answer. I've listed comments explaining each step. I hope this helps. : )
import { Subject } from 'rxjs/Subject';
export class ClassName {
// ------ Creating the observable ----------
// Create a subject - The thing that will be watched by the observable
public stringVar = new Subject<string>();
// Create an observable to watch the subject and send out a stream of updates (You will subscribe to this to get the update stream)
public stringVar$ = this.stringVar.asObservable() //Has a $
// ------ Getting Your updates ----------
// Subscribe to the observable you created.. data will be updated each time there is a change to Subject
public subscription = this.stringVar$.subscribe(data => {
// do stuff with data
// e.g. this.property = data
});
// ------ How to update the subject ---------
// Create a method that allows you to update the subject being watched by observable
public updateStringSubject(newStringVar: string) {
this.stringVar.next(newStringVar);
}
// Update it by calling the method..
// updateStringSubject('some new string value')
// ------- Be responsible and unsubscribe before you destory your component to save memory ------
ngOnDestroy() {
this.subscription.unsubscribe()
}
}
这篇关于使用Observable检测变量的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!