gpt4 book ai didi

javascript - 使用 Observable 检测变量的变化

转载 作者:可可西里 更新时间:2023-11-01 01:39:24 24 4
gpt4 key购买 nike

我想我误解了应该如何使用 Observables。我想输入一个值,当值发生变化时,它应该发出新值。我以为那是他们的目的,但所有的教程和文档似乎都没有这样做,但与此同时,我总是看到他们以这种方式应用。例如,在 Angular 中,当您订阅“FirebaseListObservable”时,当 firebase 中的值更改时,它会触发订阅中的快照。我想为我自己的变量做那个。假设我只有一个字符串变量,当它发生变化时,它会触发所有订阅。

最佳答案

通常我会将我的可观察对象放在组件中订阅的服务中,但为了方便回答这个问题,我将它们全部捆绑在一个类中。我列出了解释每个步骤的评论。我希望这有帮助。 :)

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

关于javascript - 使用 Observable 检测变量的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46132012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com