Skip to content

Instantly share code, notes, and snippets.

@NyaGarcia
Created June 27, 2022 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NyaGarcia/25aae4e57cb15721de334f2c33822f23 to your computer and use it in GitHub Desktop.
Save NyaGarcia/25aae4e57cb15721de334f2c33822f23 to your computer and use it in GitHub Desktop.
Handling subscriptions in the Pokemon component
import { Component, OnInit } from '@angular/core';
import { Observable, Subject, filter, takeUntil, tap } from 'rxjs';
import { FormComponent } from './components/form/form.component';
import { MatDialog } from '@angular/material/dialog';
import { PokedexFirestoreService } from 'src/app/core/pokedex-firestore.service';
import { Pokemon } from './interfaces/pokemon.interface';
@Component({
selector: 'app-pokemon',
templateUrl: './pokemon.component.html',
styleUrls: ['./pokemon.component.scss'],
})
export class PokemonComponent implements OnInit {
allPokemon$: Observable<Pokemon[]>;
selectedPokemon?: Pokemon;
destroyed$ = new Subject<void>();
constructor(
private readonly pokedexService: PokedexFirestoreService,
private readonly dialog: MatDialog
) {}
ngOnInit(): void {
this.allPokemon$ = this.pokedexService.getAll();
}
addPokemon() {
const dialogRef = this.dialog.open(FormComponent, {
data: {},
width: '40%',
});
dialogRef
.afterClosed()
.pipe(
filter(Boolean),
tap((pokemon) => this.pokedexService.create(pokemon)),
takeUntil(this.destroyed$)
)
.subscribe();
}
updatePokemon() {
const dialogRef = this.dialog.open(FormComponent, {
data: { ...this.selectedPokemon },
width: '40%',
});
dialogRef
.afterClosed()
.pipe(
filter(Boolean),
tap((pokemon) => this.pokedexService.update(pokemon)),
tap((pokemon) => this.selectPokemon(pokemon)),
takeUntil(this.destroyed$)
)
.subscribe();
}
selectPokemon(pokemon: Pokemon) {
this.selectedPokemon = pokemon;
}
deletePokemon() {
this.pokedexService.delete(this.selectedPokemon!.id);
this.selectedPokemon = undefined;
}
ngOnDestroy() {
this.destroyed$.next();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment