使用 Observable 检测变量的变化 [英] Using an Observable to detect a change in a variable

查看:18
本文介绍了使用 Observable 检测变量的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我误解了 Observable 应该如何使用.我想放入一个值,当值改变时它应该发出新值.我认为这就是它们的用途,但所有教程和文档似乎都没有这样做,但与此同时,我总是看到它们以这种方式应用.例如,在 angular 中,当您订阅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.

推荐答案

通常我会将我的 observables 放在组件中订阅的服务中,但为了这个答案的方便,我将它们全部捆绑在一个类中.我列出了解释每个步骤的注释.我希望这有帮助.:)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆