使用Observable检测变量的变化

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)

  • 假装主体是某种动物,可观察的是记录主题的相机.如果受试者处于睡眠状态,则观察者将作为事件睡着.你通过观看动物星球的电视纪录片来订阅这个哈哈 (10认同)