Handling Subscriptions in Angular 2
Reactive programming is gaining huge momentum in new frameworks and Rxjs is a front runner in Reactive Programming frameworks. Many a time you create your own Observables , Subject or BehaviourSubject while working with Angular 2 or in general across different Javascript frameworks.
its always a good practice to deal with the subscriptions you have created in your components, try not to create subscriptions in your services, services should just pass a subscribe-able object and component should be responsible for dealing with those subscriptions, so the question arises how should these subscriptions be, the way i handle subscriptions is to unsubscribe on OnDestroy, for this easiest way i have found is to inherit your component from a BaseComponet which implements NgDestroy and maintains an Array of all your subscriptions per component, here is a snippet of the same
BaseComponent
import { OnDestroy } from "@angular/core"
import { Subscription } from "rxjs/Subscription";
export class BaseComponent implements OnDestroy {
protected subscriptions: Subscription[] = [];
constructor() { }
ngOnDestroy(): void {
this.subscriptions.forEach((subscription) => {
if (process.env != 'production') {
console.log('unsuscribing:');
console.log(subscription);
}
subscription.unsubscribe()
});
}
}
Basecomponent maintains an Array of all Subscriptions and it will unsubscribe these on NgDestroy.
MainComponent
All other components inherit from your BaseComponent and will push all the required subscriptions to the Array, below is a code snippet
import { Component} from '@angular/core';
import { UserService } from "../services/UserService";
import { Observable, Subscription, Subject } from "rxjs";
import { Router } from "@angular/router";
import { NgRedux, select } from "@angular-redux/store/lib";
import { IAppState } from "../StateStore/Store";
import { BaseComponent } from "../sharedcomponents/BaseComponent";
@Component({
templateUrl: "./login.html",
selector: 'login'
})
export class LoginComponent extends BaseComponent {
@select((store: IAppState) => store.user) loggedInUser: Observable<any>;
constructor(private userService: UserService, private router: Router,
private ngRedux: NgRedux<IAppState>) {
super();
this.subscriptions.push(this.loggedInUser.subscribe(this.loggedIn));
}
private loggedIn = (user: any) => {
if (user !== null) {
this.router.navigate(['/home']);
}
}
}
i will be very interested to know how others are dealing with subscriptions and what approach they follow to Unsubscribe. Hope this helps.