Reputation: 310
I am wondering if there's another way to auto subscribe/unsubscribe from an observable? I have seen async pipe mostly in html template, but what about when I want to do something in my component class, talking about when you're working in an angular project for example.
Upvotes: 3
Views: 2108
Reputation: 11345
You can probably create a base class to do so and extend it with your component class, then you don't have to repeat the ngDestory handling for every component that you created.
export class BaseComponent implements OnDestroy {
public _subscriptions: Subscription[] = [];
addSubscription(...sub): Subscription | Subscription[] {
this._subscriptions.concat(sub);
return sub;
}
ngOnDestroy(): void {
this._subscriptions.forEach(s =>
s.unsubscribe()
);
}
}
example usuage
class MyComp extends BaseComponent{
ngOnInit(){
this.addSubscription(interval(1000).subscribe())
}
}
Upvotes: 1
Reputation: 1138
I would recommend one of the following unsubscribe methods:
takeUntil
operator:@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit, OnDestroy {
private readonly componentDestroyed$ = new Subject();
ngOnDestroy(): void { this.componentDestroyed$.next() }
ngOnInit(): void {
myObservable$.pipe(takeUntil(this.componentDestroyed$)).subscribe(() => {
// your code here...
})
}
}
Upvotes: 4
Reputation: 303
You can make use of a behavior subject like this
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
export class ComponentA implements OnInit, OnDestroy {
private componentUnload$ = new Subject<boolean>();
constructor(
public dataService: DataService,
) {}
ngOnInit() {
this.dataService.items$ // here, you are calling an observable
.pipe(takeUntil(this.componentUnload$))
.subscribe(items => {
this.items = items;
});
}
ngOnDestroy(): void {
this.componentUnload$.next(true);
}
Upvotes: 0