Last active
November 6, 2024 23:26
-
-
Save dmorosinotto/efae3315e1339597fca0921b7c944385 to your computer and use it in GitHub Desktop.
Angular BaseComponent with handle destroy$ and takeUntil pattern to unsubscribe!
This file contains 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 { Directive, OnDestroy } from "@angular/core"; | |
import { Subject } from "rxjs"; | |
import { takeUntil } from "rxjs/operators"; | |
@Directive() // Needed only for Angular v9+ strict mode that enforce decorator to enable Component inheritance | |
export abstract class BaseComponent implements OnDestroy { | |
// _destroy$ is LAZY: it'll be created (and allocate memory) only if you use takeUntilDestroy | |
private _destroy$?: Subject<void>; | |
protected takeUntilDestroy = <T>() => { | |
if (!this._destroy$) this._destroy$ = new Subject<void>(); // LAZY Subject | |
return takeUntil<T>(this._destroy$); | |
}; | |
ngOnDestroy() { | |
if (this._destroy$) { | |
this._destroy$.next(); | |
this._destroy$.complete(); | |
} | |
} | |
} |
This file contains 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, OnInit } from '@angular/core'; | |
import { ActivatedRoute } from '@angular/router'; | |
import { BaseComponent } from './base.component'; | |
@Component({ | |
selector: 'app-sample-use', | |
template: ` | |
<p> | |
sample-use works! | |
{{ pars | json }} | |
</p> | |
` | |
}) | |
export class SampleUseComponent extends BaseComponent implements OnInit { | |
public pars: { [key:string]: any } = {}; | |
constructor(private route: ActivatedRoute) { | |
super() | |
} | |
ngOnInit() { | |
this.sampleSubcribe(true); | |
} | |
sampleSubcribe(log:boolean = false){ | |
this.route.paramMap | |
.pipe(this.takeUntilDestroy()) //NOTICE takeUntilDestroy PATTERN TO AUTOMATIC unsubscribe! | |
.subscribe(pm => { | |
const obj = {}; | |
pm.keys.forEach(k => { | |
obj[k] = pm.get(k); | |
}); | |
if (log) console.log({ pm, obj }) | |
this.pars = obj; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment