In Angular 2 are there any specific pitfalls regarding memory management, I should be aware of?
What are the best practices to manage the state of components in orde
You do not have to unsubscribe from standard subscriptions like after http.get(). But you DO have to unsubscribe from subscription on your custom Subjects. If you have some component and inside it you subscribing to some Subject in your service, then every time you showing that component new subscription will be added to the Subject.
Please check this out: Good solution to make your components 'clean'
My personal approach - all my components are extended from this nice class:
import { OnDestroy, OnInit } from '@angular/core';
import { Subject } from 'rxjs/Subject';
/**
* A component that cleans all subscriptions with oneself
* https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription
* @class NeatComponent
*/
export abstract class NeatComponent implements OnDestroy, OnInit {
// Add '.takeUntil(this.ngUnsubscribe)' before every '.subscrybe(...)'
// and this subscriptions will be cleaned up on component destroy.
protected ngUnsubscribe: Subject = new Subject();
public ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
public ngOnInit(){}
}
And I just adding super() call to constructor and .takeUntil(this.ngUnsubscribe) before every subscribe:
import { NeatComponent } from '../../types/neat.component';
@Component({
selector: 'category-selector',
templateUrl: './category-selector.component.pug'
})
export class CategorySelectorComponent extends NeatComponent {
public constructor(
private _shopService: ShopsService
) { super(); }
public ngOnInit() {
this._shopService.categories.takeUntil(this.ngUnsubscribe)
.subscribe((categories: any) => {
// your code here
})
}
}