How to unsubscribe in Angular2

How to unsubscribe in Angular2? RxJS seems to have a dispose method, but I can't figure out how to access it. Therefore, I have code that has access to the EventEmitter and subscribes to it, for example:

var mySubscription = someEventEmitter.subscribe( (val) => { console.log('Received:', val); }, (err) => { console.log('Received error:', err); }, () => { console.log('Completed'); } ); 

How can I use mySubscription to unsubscribe?

+67
javascript angular rxjs
Dec 23 '15 at 19:46
source share
8 answers

Do you want to unsubscribe?

 mySubscription.unsubscribe(); 
+99
Dec 23 '15 at 19:54
source share
— -

I thought I also put my two cents. I am using this template:

 import { Component, OnInit, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; @Component({ selector: 'my-component', templateUrl: 'my.component.html' }) export class MyComponent implements OnInit, OnDestroy { private subscriptions: Array<Subscription> = []; public ngOnInit(): void { this.subscriptions.push(this.someService.change.subscribe(() => { [...] })); this.subscriptions.push(this.someOtherService.select.subscribe(() => { [...] })); } public ngOnDestroy(): void { this.subscriptions.forEach((subscription: Subscription) => { subscription.unsubscribe(); }); } } 

EDIT

I read the documentation the other day and found a more recommended template:

ReactiveX / RxJS / Subscription

Pros:

It manages new subscriptions internally and adds some neat checks. Prefer this method in function :).

Minuses:

At 100% it is not clear what a code stream is and how a subscription affects. It is also not clear (just looking at the code) how it works with private subscriptions, and if all subscriptions are closed, if unsubscribe is called.

 import { Component, OnInit, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; @Component({ selector: 'my-component', templateUrl: 'my.component.html' }) export class MyComponent implements OnInit, OnDestroy { private subscription: Subscription = new Subscription(); public ngOnInit(): void { this.subscription.add(this.someService.change.subscribe(() => { [...] })); this.subscription.add(this.someOtherService.select.subscribe(() => { [...] })); } public ngOnDestroy(): void { /* * magic kicks in here: All subscriptions which were added * with "subscription.add" are canceled too! */ this.subscription.unsubscribe(); } } 
+41
Feb 16 '17 at 12:56 on
source share

EDIT: This does not apply to RxJS 5, which is used by angular2.

I would think that you are looking for the dispose method on Disposable .

the subscribe method returns a Disposable () link

I cannot find it more explicitly in the docs, but this works ( jsbin ):

 var observable = Rx.Observable.interval(100); var subscription = observable.subscribe(function(value) { console.log(value); }); setTimeout(function() { subscription.dispose(); }, 1000) 

Oddly enough, unsubscribing works for you until it works for me ...

+9
Dec 23 '15 at 20:24
source share

Too many different explanations for unsubscribing from Observables for ng2, it took a long time to find the right answer. The following is a working example (I tried to compress mousemove).

 import {Injectable, OnDestroy} from "@angular/core"; import {Subscription} from "rxjs"; @Injectable() export class MyClass implements OnDestroy { mouseSubscription: Subscription; //Set a variable for your subscription myFunct() { // I'm trying to throttle mousemove const eachSecond$ = Observable.timer(0, 1000); const mouseMove$ = Observable.fromEvent<MouseEvent>(document, 'mousemove'); const mouseMoveEachSecond$ = mouseMove$.sample(eachSecond$); this.mouseSubscription = mouseMoveEachSecond$.subscribe(() => this.doSomethingElse()); } doSomethingElse() { console.log("mouse moved"); } stopNow() { this.mouseSubscription.unsubscribe(); } ngOnDestroy() { this.mouseSubscription.unsubscribe(); } } 
+4
Jan 11 '17 at 15:48
source share
 ngOnDestroy(){ mySubscription.unsubscribe(); } 

They prefer to unsubscribe from rxjs when they unsubscribe when a component is destroyed, that is, removal from the DOM to prevent unnecessary memory leaks.

+2
Dec 02 '16 at 10:27
source share

I prefer to personally use the Subject to close all subscriptions that the component could have at the stage of the destruction of the life cycle, which can be achieved as follows:

 import { Component} from '@angular/core'; import { Subject } from "rxjs/Rx"; @Component({ selector: 'some-class-app', templateUrl: './someClass.component.html', providers: [] }) export class SomeClass { private ngUnsubscribe: Subject<void> = new Subject<void>(); //This subject will tell every subscriptions to stop when the component is destroyed. //********** constructor() {} ngOnInit() { this.http.post( "SomeUrl.com", {}, null ).map( response => { console.log( "Yay." ); }).takeUntil( this.ngUnsubscribe ).subscribe(); //This is where you tell the subscription to stop whenever the component will be destroyed. } ngOnDestroy() { //This is where we close any active subscription. this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); } } 
+2
Sep 08 '17 at 14:30
source share

Using

 if(mySubscription){ mySubscription.unsubscribe(); } 
+1
Aug 09 '16 at 12:59 on
source share

The recommended approach is to use RxJS statements, such as the takeUntil statement . The following is a code snippet showing how to use it: -

 import { Component, OnInit, OnDestroy } from '@angular/core'; import { interval, Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent implements OnInit, OnDestroy { private ngUnsubscribe = new Subject(); constructor() { } ngOnInit() { var observable1 = interval(1000); var observable2 = interval(2000); observable1.pipe(takeUntil(this.ngUnsubscribe)).subscribe(x => console.log('observable1: ' + x)); observable2.pipe(takeUntil(this.ngUnsubscribe)).subscribe(x => console.log('observable2: ' + x)); } ngOnDestroy() { this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); } } 

You can find a detailed explanation of the topic here.

+1
Jun 06 '18 at 16:24
source share



All Articles