Created
January 14, 2021 12:09
-
-
Save izerozlu/9debf808af5295d6aef63710400e1024 to your computer and use it in GitHub Desktop.
Angular SubscriptionHandlerService example.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Component} from '@angular/core'; | |
import {SubscriptionHandlerService} from '../../services/subscription-handler.service'; | |
@Component({ | |
selector: 'some-component', | |
templateUrl: './some-component.component.html', | |
styleUrls: ['./some-component.component.scss'], | |
providers: [SubscriptionHandlerService] | |
}) | |
export class SomeComponent { | |
constructor( | |
private subscriptionHandlerService: SubscriptionHandlerService | |
) { | |
} | |
private listenToSomething() { | |
const subscription = this.someObservable.subscribe(() => this.somethingToDo()); | |
this.subscriptionHandlerService.add(subscription); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Injectable, OnDestroy} from '@angular/core'; | |
import {Subscription} from 'rxjs'; | |
@Injectable() | |
export class SubscriptionHandlerService implements OnDestroy { | |
private subscriptions: Subscription[] = []; | |
constructor() { | |
} | |
public ngOnDestroy() { | |
this.subscriptions.forEach((subscription: Subscription) => subscription.unsubscribe()); | |
} | |
public add(subscription: Subscription) { | |
this.subscriptions.push(subscription); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment