import { ChangeDetectionStrategy, Component, inject, OnInit } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { ActivatedRoute, Router } from '@angular/router'; import { MatSnackBar } from '@angular/material/snack-bar'; import { httpErrorMessage } from 'src/app/helpers/http-error'; import { Tutorial } from 'src/app/models/tutorial.model'; import { TutorialService } from 'src/app/services/tutorial.service'; @Component({ selector: 'app-tutorial-details', templateUrl: './tutorial-details.component.html', styleUrls: ['./tutorial-details.component.scss'], changeDetection: ChangeDetectionStrategy.Eager, standalone: false }) export class TutorialDetailsComponent implements OnInit { private readonly tutorialService = inject(TutorialService); private readonly route = inject(ActivatedRoute); private readonly router = inject(Router); private readonly snackBar = inject(MatSnackBar); currentTutorial: Tutorial = { title: '', description: '', published: false }; notFound = false; ngOnInit(): void { this.tutorialService.get(this.route.snapshot.params['id']).subscribe({ next: data => this.currentTutorial = data, error: err => { this.notFound = true; this.showError(err); } }); } updatePublished(published: boolean): void { const data = { ...this.currentTutorial, published }; this.tutorialService.update(this.currentTutorial.id, data).subscribe({ next: () => { this.currentTutorial.published = published; this.notify(published ? 'Tutorial was published' : 'Tutorial was unpublished'); }, error: err => this.showError(err) }); } updateTutorial(): void { this.tutorialService.update(this.currentTutorial.id, this.currentTutorial).subscribe({ next: () => this.notify('Tutorial was saved'), error: err => this.showError(err) }); } deleteTutorial(): void { if (!confirm(`Delete "${this.currentTutorial.title}"?`)) { return; } this.tutorialService.delete(this.currentTutorial.id).subscribe({ next: () => { this.notify('Tutorial was deleted'); this.router.navigate(['/tutorials']); }, error: err => this.showError(err) }); } private notify(message: string): void { this.snackBar.open(message, 'OK', { duration: 3000 }); } private showError(err: HttpErrorResponse): void { this.snackBar.open(httpErrorMessage(err), 'OK', { duration: 5000 }); } }