Unsubscribe

A leiratkozást azért kell megcsinálnunk, mert az angular úgy működik, hogy amikor egy komponens működése véget ér, attól függetlenül ezek a feliratkozások még életben maradnak. És ha életben hagyjuk a felirtkozásokat, akkor úgynevezett Memory Leak-ek keletkezhetnek. Tehát olyan funkcionalitás maradhat életben, amire a user interfacen már nincsen szükségünk.

A sablonban (html-ben) történt async feliratkozásokat ez a probléma nem érinti.

ngOnDestroy

A leirtkozás itt történik, tipikusan takarító jellegű műveleteket végzünk el.

import { Component, OnDestroy, OnInit } from '@angular/core';
import { BehaviorSubject, catchError, of, Subject, Subscription, switchMap, tap } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit, OnDestroy {
  elemek$ = new BehaviorSubject([]);

  isPending$ = new Subject();

  constructor(private http: HttpClient) {}

  refresh$ = new Subject().pipe(
    tap(() => {
      this.isPending$.next(true);
    }),
    switchMap(() => this.http.get('https://kodbazis.hu/api/cimek')),
    catchError((hiba) => {
      alert('hiba történt');
      return of([]);
    }),
    tap((valasz: any) => {
      this.isPending$.next(false);
      this.elemek$.next(valasz);
    })
  );

  delete$ = new Subject().pipe(
    tap(() => {
      this.isPending$.next(true);
    }),
    switchMap((i) => this.http.delete('https://kodbazis.hu/api/cimek/' + i)),
    tap(() => {
      this.isPending$.next(false);
      // @ts-ignore
      this.refresh$.next('');
    })
  );

  create$ = new Subject().pipe(
    tap(() => {
      this.isPending$.next(true);
    }),
    switchMap((ujCim) =>
      this.http.post('https://kodbazis.hu/api/cimek', { cim: ujCim })
    ),
    tap(() => {
      this.isPending$.next(false);
      // @ts-ignore
      this.refresh$.next('');
    })
  );

  feliratkozasok: Subscription[] = [];

  ngOnInit(): void {
    const feliratkozas1 = this.refresh$.subscribe();
    const feliratkozas2 = this.delete$.subscribe();
    const feliratkozas3 = this.create$.subscribe();

    this.feliratkozasok.push(feliratkozas1, feliratkozas2, feliratkozas3)

    // @ts-ignore
    this.refresh$.next('');
  }

  elemTorlese(i: number) {
    // @ts-ignore
    this.delete$.next(i);
  }

  onSubmit(e: any) {
    e.preventDefault();
    const ujErtek = e.target.elements.cim.value;
    e.target.reset();
    // @ts-ignore
    this.create$.next(ujErtek);
  }

  ngOnDestroy(): void {
    for(let feliratkozas of this.feliratkozasok) {
      feliratkozas.unsubscribe();
    }
  }
}
Was this page helpful?