20

I'm making a drag and drop application and I have created an observable to the mouse position, that repositions my drag-object.

mouseMove$: any;

constructor(){
  this.mouseMove$ = Observable.fromEvent(document, 'mousemove')
    .do((mouseevent: MouseEvent) => {
      if (document.getElementById("drag-object")){
        document.getElementById("drag-object").style.left = (mouseevent.clientX) + 'px';
        document.getElementById("drag-object").style.top = (mouseevent.clientY) + 'px';
      }
  });

With this implementation I have no problem subscribing in this way:

this.mouseMove$.subscribe();

however I cannot seem to unsubscribe by either:

this.mouseMove$.unsubscribe();

or

this.mouseMove$.dispose();

in either case I get the following type of error:

TypeError: this.mouseMove$.unsubscribe is not a function ...

I'm not sure if this has to do with the mouseMove$ type of any, but setting the type as Observable and Observable<MouseEvent> did not work. What am I not understanding here?

Nate May
  • 3,814
  • 7
  • 33
  • 86

4 Answers4

46

You're probably using a newer version of RxJS, where there has been an API change where Observable.subscribe returns a Disposable, from which you call .unsubscribe now (dispose became unsubscribe in RxJS5). Unfortunately there are still lots of old tutorials and blog posts out there doing it "the old way", resulting in this confusion.

Thus, your code should be

let disposeMe = this.mouseMove$.subscribe();

and, after you're done

disposeMe.unsubscribe();

For a full list of API changes from Version 4 to 5, check this file.

Georg Grab
  • 2,271
  • 1
  • 18
  • 28
4

make sure your this.mouseMove$ is an observable first:

if (this.mouseMove$ !== undefined) {
  this.mouseMove$.unsubscribe();
}

probably in your case, you unsubscribe before this.mouseMove$ has not been assigned any value yet.

Bo Chen
  • 156
  • 9
0
  this.getValue= this.ntUser.salesEnquiry()
      .subscribe(
        (result) => {
    // some action
          this.getdataapi.unsubscribe();
        },
        (error) => {
          // some action
        }
      );
  }
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
DinoRaj p
  • 21
  • 3
-2

Take a look at brianflove.com.

By setting mouseMove$: ISubscription, should take care of the issue.

Roger
  • 1