Jus*_*s10 15 javascript observable rxjs
我想我误解了Observables应该如何使用.我想要输入一个值,当值更改时,它应该发出新值.我认为这就是它们的用途,但是所有教程和文档似乎都没有这样做,但与此同时,我总是看到它们以这种方式应用.例如,当您订阅"FirebaseListObservable"时,以角度为单位,当firebase中的值更改时,它将触发订阅中的快照.我想为我自己的变量做这个.假设我只有一个字符串变量,当它发生变化时,会触发任何订阅.
Jon*_*002 23
通常我会在可以在组件中订阅的服务中使用我的observable,但为了方便这个答案,我将它们全部捆绑在一个类中.我列出了解释每一步的评论.我希望这有帮助.:)
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()
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10024 次 |
| 最近记录: |