简体   繁体   中英

How to call a method of a class from an rxjs observable subscription

Could I please ask:

This code works fine:

class MyClass
{
  constructor()
  {
    this.m_observable = Rx.Observable.of(1, 2);
    
      this.m_observable.subscribe(
                                 function (x) {alert(x);}
                                 );
  }
  
  DoIt(x)
  {
    alert(5 * x);
  }
}

When I create a new instance of the class I see "1" then "2".

I would like to call the DoIt method of the class when the subscription fires, this code does not work, I see no alerts:

class rxjsShapeShifter
{
  constructor()
  {
    this.m_observable = Rx.Observable.of(1, 2);
    
      this.m_observable.subscribe(
                                 this.DoIt;
                                 );
  }
  
  DoIt(x)
  {
    alert(5 * x);
  }
}

How can I call that method from the observable subscription?

Thanks for any help.

I think you have typo in your subscribe . The second code of your should be:

    constructor() {
      this.m_observable = Rx.Observable.of(1, 2);
      this.m_observable.subscribe(this.DoIt);
    }
    
    DoIt(x) {
      alert(5 * x);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM