File tree Expand file tree Collapse file tree 1 file changed +12
-2
lines changed Expand file tree Collapse file tree 1 file changed +12
-2
lines changed Original file line number Diff line number Diff line change @@ -66,13 +66,23 @@ When you should unsubscribe when the component gets destroyed.
6666# Recommended ways to unsubscribe
6767One way is to assign the subscription to a class property and manually unsubscribe in `` ngOnDestroy `` .
6868```
69+ private subscription: Subscription;
70+
71+ ngOnInit() {
72+ this.subscription = timer(0, 1000)
73+ .subscribe(() => {
74+ this.counter++;
75+ this.titleService.setTitle('Counter ' + this.counter);
76+ });
77+ }
78+
6979ngOnDestroy() {
7080 // Avoid side effects and memory leak by unsubscribing:
7181 this.subscription.unsubscribe();
7282}
7383```
7484
75- However, its not feasible for large applications with many subscriptions,
85+ However, it's not feasible for large applications with many subscriptions,
7686as its cumbersome to write and introduces a lot of obfuscating code.
7787
7888Another way of handling it, would be to collect all subscriptions and unsubscribe them at once:
@@ -133,7 +143,7 @@ ngOnDestroy() {
133143}
134144```
135145When the component gets destroyed, the observable `` ngDestroy `` gets completed, causing the subscriptions to complete.
136- Thus memory leaks and side effects are avoided.
146+ Thus memory leaks and unwanted side effects are avoided.
137147
138148Drawbacks: As with the other methods, it's still quite verbose and error-prone.
139149
You can’t perform that action at this time.
0 commit comments