@NgModule({
imports: [
FormsModule
],
})
Gyermek mutatása
import { Component, OnInit } from '@angular/core';
import { interval } from 'rxjs';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {
src = interval(2000);
id = Date.now();
constructor() { }
ngOnInit(): void {
console.log('Az alkalmazás indul' + this.id)
this.src.subscribe(() => {
console.log('Érkezett: ' + this.id)
})
}
ngOnDestroy() {
console.log('Komponens vége' + this.id);
}
}
child works!
import { Component, OnInit } from '@angular/core';
import { interval } from 'rxjs';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {
src = interval(2000);
id = Date.now();
constructor() { }
ngOnInit(): void {
console.log('Az alkalmazás indul' + this.id)
this.src.subscribe(() => {
console.log('Érkezett: ' + this.id)
})
}
ngOnDestroy() {
console.log('Komponens vége' + this.id);
}
}
===== Leiratkozás =====
A gyermek komponenseben, ahol feliratkoztunk tároljuk a feliratkozást, majd
leiratkozunk a komponense megszűnésekor.
Létrehozunk egy obs objektumot a **child.component.ts** fájlban:
obs !: Subscription;
A feliratkozás eredményét tároljuk az obs objektumban:
this.obs = this.src.subscribe(() => {
console.log('Érkezett: ' + this.id)
})
A komponens megszűnésekor leiratkozunk:
ngOnDestroy() {
console.log('Komponens vége' + this.id);
this.obs.unsubscribe();
}
Teljes kód:
import { Component, OnInit } from '@angular/core';
import { interval, Subscription } from 'rxjs';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {
src = interval(2000);
id = Date.now();
obs !: Subscription;
constructor() { }
ngOnInit(): void {
console.log('Az alkalmazás indul' + this.id)
this.obs = this.src.subscribe(() => {
console.log('Érkezett: ' + this.id)
})
}
ngOnDestroy() {
console.log('Komponens vége' + this.id);
this.obs.unsubscribe();
}
}
===== Linkek =====
* https://www.tektutorialshub.com/angular/unsubscribing-from-an-observable-in-angular/ (2023)
* https://www.lucaspaganini.com/academy/angular-automatically-unsubscribe-observables-on-destroy (2023)
* https://levelup.gitconnected.com/unsubscribing-in-angular-the-right-way-6ed82be43ccc (2023)