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 { this.subscription.unsubscribe(); } }
Nightking Feb 16 '17 at 12:56 on 2017-02-16 12:56
source share