Ora inseriremo un form che ci permetterà di creare nuovi libri e di aggiungerli alla nostra collezione della library.
Per prima cosa creiamo due nuovi componenti:
BookListComponent
# ng generate component modules/library/components/BooksList
CREATE src/app/modules/library/components/books-list/books-list.component.scss (0 bytes)
CREATE src/app/modules/library/components/books-list/books-list.component.html (25 bytes)
CREATE src/app/modules/library/components/books-list/books-list.component.spec.ts (614 bytes)
CREATE src/app/modules/library/components/books-list/books-list.component.ts (230 bytes)
AddNewBookComponent
# ng generate component modules/library/components/AddNewBook
CREATE src/app/modules/library/components/add-new-book/add-new-book.component.scss (0 bytes)
CREATE src/app/modules/library/components/add-new-book/add-new-book.component.html (27 bytes)
CREATE src/app/modules/library/components/add-new-book/add-new-book.component.spec.ts (622 bytes)
CREATE src/app/modules/library/components/add-new-book/add-new-book.component.ts (237 bytes)
Ora riorganizziamo il codice. Valutiamo di spostare la struttura comune, come un <div class="library">, nel file principale app.component.html. Questo garantisce un layout coerente tra le diverse viste gestite dal router.
<!-- src/app/app.component.html -->
<h1>{{ title }}</h1>
<div class="library">
<app-library></app-library>
<router-outlet></router-outlet>
</div>
Ora dobbiamo aggiungere il metodo corrispondente nel nostro app.component.ts per gestire l’evento di click del pulsante.
// src/app/app.component.ts
import { Component, OnInit } from "@angular/core";
import { RouterOutlet } from "@angular/router";
import { LibraryComponent } from "./modules/library/components/library/library.component";
import { MatButtonModule } from "@angular/material/button";
import { MatIconModule } from "@angular/material/icon";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrl: "./app.component.scss",
imports: [RouterOutlet, LibraryComponent, MatButtonModule, MatIconModule],
})
/**
* The `AppComponent` serves as the root component of the Library application.
* It initializes the application state and interacts with the `LibraryService`
* to fetch and display a list of books.
*
* @implements {OnInit}
*/
export class AppComponent implements OnInit {
title = "Library";
constructor() {}
ngOnInit(): void {}
}
Ora spostiamo tutto il contenuto del nostro componente library nel componente books-list:
<mat-form-field class="search-form-field">
<mat-label>Search</mat-label>
<input matInput type="text" placeholder="Search for books" [(ngModel)]="searchText" (ngModelChange)="onSearchInputChange($event)" />
@if (searchText) {
<button matSuffix mat-icon-button aria-label="Clear" (click)="clearFilter()">
<mat-icon>close</mat-icon>
</button>
}
</mat-form-field>
<table *ngIf="books" mat-table [dataSource]="books" class="library-table" matSort matSortActive="ordering" matSortDirection="desc" (matSortChange)="handleSortEvent($event)">
<!-- Title Column -->
<ng-container matColumnDef="title">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Title</th>
<td mat-cell *matCellDef="let row">{{ row.title }}</td>
</ng-container>
<!-- State Column -->
<ng-container matColumnDef="author_name">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Author</th>
<td mat-cell *matCellDef="let row">{{ row.author_name }}</td>
</ng-container>
<!-- Created Column -->
<ng-container matColumnDef="publication_date">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Published</th>
<td mat-cell *matCellDef="let row">{{ row.publication_date | date }}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
<mat-paginator
#paginator
[pageSize]="pageSize"
[pageSizeOptions]="pageSizeOptions"
[length]="totalBooks"
[pageIndex]="pageIndex"
(page)="handlePageEvent($event)"
aria-label="Select page"
>
</mat-paginator>
import { Component, OnInit } from "@angular/core";
import { Book, LibraryService, PaginatedBookList, LibraryBooksListRequestParams } from "../../../core/api/v1";
import { DatePipe, NgIf } from "@angular/common";
import { PageEvent, MatPaginatorModule } from "@angular/material/paginator";
import { MatTableModule } from "@angular/material/table";
import { Sort, MatSortModule, SortDirection } from "@angular/material/sort";
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatInputModule } from "@angular/material/input";
import { FormsModule } from "@angular/forms";
import { MatIconModule } from "@angular/material/icon";
import { MatButtonModule } from "@angular/material/button";
import { debounceTime, Subject } from "rxjs";
@Component({
selector: "app-books-list",
imports: [NgIf, MatPaginatorModule, MatTableModule, MatSortModule, DatePipe, MatFormFieldModule, MatInputModule, FormsModule, MatButtonModule, MatIconModule],
templateUrl: "./books-list.component.html",
styleUrl: "./books-list.component.scss",
})
/**
* The `LibraryComponent` is responsible for displaying a paginated and sortable list of books
* in the library. It interacts with the `LibraryService` to fetch data and provides functionality
* for handling user interactions such as pagination and sorting.
*
* @remarks
* This component uses Angular Material's table and pagination components to display and manage
* the list of books. It maintains the current state of pagination, sorting, and the list of books
* retrieved from the API.
*
* @property {string} title - The title of the component, displayed in the UI.
* @property {Book[]} books - The array of books currently displayed in the table.
* @property {number} totalBooks - The total number of books available in the library.
* @property {number} pageSize - The number of books displayed per page.
* @property {number} pageIndex - The current page index (0-based).
* @property {PageEvent | undefined} pageEvent - The latest pagination event triggered by the user.
* @property {number[]} pageSizeOptions - The available options for the number of books per page.
* @property {string} ordering - The current sorting order for the list of books.
* @property {string[]} displayedColumns - The columns displayed in the table.
*
* @method ngOnInit - Lifecycle hook that initializes the component and fetches the initial list of books.
* @method handlePageEvent - Handles pagination events and updates the list of books accordingly.
* @method handleSortEvent - Handles sorting events and updates the list of books based on the selected criteria.
* @method getBooks - Fetches a paginated and sorted list of books from the library service.
* @method onSearchInputChange - Emits the new search text to the searchSubject.
* @method performSearch - Executes the search logic based on the current search text.
*/
export class BooksListComponent implements OnInit {
books: Book[] = [];
totalBooks = 0;
pageSize = 5;
pageIndex = 0;
pageEvent: PageEvent | undefined;
pageSizeOptions = [5, 10, 25];
ordering = "title";
displayedColumns: string[] = ["title", "author_name", "publication_date"];
searchText = "";
private searchSubject = new Subject<string>();
constructor(private readonly libraryService: LibraryService) {}
/**
* Lifecycle hook that is called after the component's view has been initialized.
* Initializes the component by fetching the list of books and setting up a subscription
* to handle search input with a debounce time of 300ms. When a search term is emitted,
* it updates the search text, resets the page index, and fetches the filtered list of books.
*/
ngOnInit(): void {
this.getBooks();
this.searchSubject.pipe(debounceTime(300)).subscribe((searchText) => {
this.searchText = searchText;
this.pageIndex = 0;
this.getBooks();
});
}
/**
* Handles pagination events triggered by the user.
* Updates the current page size and index based on the event,
* and fetches the updated list of books accordingly.
*
* @param e - The pagination event containing the new page size and index.
*/
handlePageEvent(e: PageEvent) {
this.pageEvent = e;
this.pageSize = e.pageSize;
this.pageIndex = e.pageIndex;
this.getBooks();
}
/**
* Handles the sorting event triggered by the user.
* Updates the sorting order and resets the page index before fetching the updated list of books.
*
* @param e - The sorting event containing the active sorting field and direction.
* @param e.active - The field by which the data should be sorted (e.g., 'publication_date', 'author_name', 'title').
* @param e.direction - The direction of sorting ('asc' for ascending, 'desc' for descending).
*/
handleSortEvent(e: Sort) {
const sortDirection: SortDirection = e.direction;
let sortActive = e.active;
if (sortActive === "publication_date") {
sortActive = "publication_date";
} else if (sortActive === "author_name") {
sortActive = "author";
} else if (sortActive === "title") {
sortActive = "title";
}
if (sortDirection === "desc") {
this.ordering = `${sortActive}`;
} else {
this.ordering = `-${sortActive}`;
}
this.pageIndex = 0;
this.getBooks();
}
/**
* Fetches a paginated list of books from the library service based on the current
* page index, page size, and ordering criteria. Updates the component's `books`
* and `totalBooks` properties with the retrieved data.
*
* @remarks
* This method constructs the request parameters and calls the `libraryBooksList`
* method of the `libraryService`. It handles the response by populating the
* `books` array with the results and updating the `totalBooks` count. Errors
* during the API call are logged to the console.
*
* @returns void
*/
/**
* Fetches a paginated list of library books based on the current search and pagination criteria.
*
* This method constructs the request parameters, including pagination, ordering, and optional search text,
* and sends a request to the library service to retrieve the list of books. The results are then assigned
* to the component's `books` property, and the total number of books is updated.
*
* @remarks
* - The `page` parameter is adjusted to match the API's 1-based pagination.
* - If a search text is provided, it is included in the request parameters.
*
* @throws Will log an error to the console if the API request fails.
*/
getBooks() {
/**
* Parameters for requesting a list of library books.
*
* @property page - The current page index incremented by 1 to match the API's 1-based pagination.
* @property pageSize - The number of items to display per page.
* @property ordering - The ordering criteria for the list of books.
* @property search - The search text to filter the list of books (optional).
*/
let params: LibraryBooksListRequestParams = {
page: this.pageIndex + 1,
pageSize: this.pageSize,
ordering: this.ordering,
};
if (this.searchText !== "") {
params["search"] = this.searchText;
}
this.libraryService.libraryBooksList(params).subscribe({
next: (data: PaginatedBookList) => {
console.log(data);
this.books = data.results || [];
this.totalBooks = data.total_records || 0;
},
error: (err) => {
console.error(err);
},
});
}
/**
* Emits the new search text to the searchSubject.
*
* @param value - The new search text entered by the user.
*/
onSearchInputChange(value: string): void {
this.searchSubject.next(value);
}
/**
* Clears the current search filter by resetting the search text and page index.
* After clearing the filter, it fetches the updated list of books.
*/
clearFilter(): void {
this.searchText = "";
this.pageIndex = 0;
this.getBooks();
}
}
Infine aggiorniamo il componente library.
<h2>Books</h2>
<app-books-list></app-books-list>
<hr />
<div class="library-footer">
<a mat-raised-button color="primary" (click)="openAddBookDialog()"> <mat-icon>add</mat-icon> Add New Book </a>
</div>
import { Component, OnInit } from "@angular/core";
import { MatIconModule } from "@angular/material/icon";
import { MatButtonModule } from "@angular/material/button";
import { BooksListComponent } from "../books-list/books-list.component";
@Component({
selector: "app-library",
imports: [BooksListComponent, MatButtonModule, MatIconModule],
templateUrl: "./library.component.html",
styleUrl: "./library.component.scss",
})
export class LibraryComponent implements OnInit {
ngOnInit(): void {}
openAddBookDialog() {
// Logic to open the dialog for adding a new book
}
}
e aggiungiamo a style.scss:
.library-footer {
margin: 20px 0 0 0;
width: 100%;
text-align: right;
}
Questo è il risultato:

Aggiungere MatDialog
Per gestire l’aggiunta di nuovi libri useremo MatDialog di Angular Material per aprire una finestra modale contenente il nostro AddNewBookComponent.
Per prima cosa assicurati che MatDialogModule sia importato. Se LibraryComponent fa parte di un NgModule, aggiungi MatDialogModule all’array imports di quel modulo. Se LibraryComponent è standalone, aggiungi MatDialogModule al suo array imports.
Poi inietta MatDialog nel costruttore di LibraryComponent e implementa il metodo openAddBookDialog.
// src/app/modules/library/components/library/library.component.ts
import { Component, OnInit } from "@angular/core";
import { MatIconModule } from "@angular/material/icon";
import { MatButtonModule } from "@angular/material/button";
import { BooksListComponent } from "../books-list/books-list.component";
import { MatDialog } from "@angular/material/dialog"; // Import MatDialog and MatDialogModule
import { AddNewBookComponent } from "../add-new-book/add-new-book.component"; // Import the component for the dialog
@Component({
selector: "app-library",
imports: [BooksListComponent, MatButtonModule, MatIconModule, MatDialogModule],
templateUrl: "./library.component.html",
styleUrl: "./library.component.scss",
})
export class LibraryComponent implements OnInit {
constructor(public dialog: MatDialog) {}
ngOnInit(): void {}
/**
* Opens a dialog window containing the AddNewBookComponent.
* Configures the dialog's width.
*/
openAddBookDialog(): void {
const dialogRef = this.dialog.open(AddNewBookComponent, {
width: "700px",
});
dialogRef.afterClosed().subscribe((result) => {
console.log("The dialog was closed");
if (result) {
console.log("Dialog result:", result);
}
});
}
}
Ora, quando si clicca sul pulsante “Add New Book”, viene chiamato il metodo openAddBookDialog, che usa il servizio MatDialog per aprire AddNewBookComponent in una finestra di dialogo modale.
Dobbiamo anche assicurarci che AddNewBookComponent sia pronto per essere usato all’interno di un dialog. Per ora il suo template predefinito è sufficiente. Ne popoleremo il template e la logica nei prossimi passaggi.
Implementare il form per aggiungere un nuovo libro
Implementiamo il form all’interno di AddNewBookComponent per acquisire i dettagli di un nuovo libro e gestirne l’invio.
Per prima cosa aggiorna il file TypeScript del componente (add-new-book.component.ts) in modo che usi ReactiveFormsModule di Angular per la gestione del form, inietti i servizi necessari come MatDialogRef e LibraryService e definisca la logica di invio del form.
// src/app/modules/library/components/add-new-book/add-new-book.component.ts
import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from "@angular/forms";
import { MatDialogRef } from "@angular/material/dialog";
import { BookRequest, LibraryBooksCreateRequestParams, LibraryService } from "../../../core/api/v1"; // Adjust path as needed
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatInputModule } from "@angular/material/input";
import { MatButtonModule } from "@angular/material/button";
import { MatDatepickerModule } from "@angular/material/datepicker";
import { DateAdapter, MAT_DATE_FORMATS, MAT_NATIVE_DATE_FORMATS, MatNativeDateModule, NativeDateAdapter } from "@angular/material/core";
import { CommonModule } from "@angular/common";
import { MatDialogModule, MatDialogTitle, MatDialogContent, MatDialogActions } from "@angular/material/dialog";
@Component({
selector: "app-add-new-book",
standalone: true, // Assuming standalone component
imports: [
CommonModule,
ReactiveFormsModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
MatDatepickerModule,
MatNativeDateModule,
MatDialogModule,
MatDialogTitle,
MatDialogContent,
MatDialogActions,
],
providers: [
{ provide: DateAdapter, useClass: NativeDateAdapter },
{ provide: MAT_DATE_FORMATS, useValue: MAT_NATIVE_DATE_FORMATS },
],
templateUrl: "./add-new-book.component.html",
styleUrls: ["./add-new-book.component.scss"],
})
export class AddNewBookComponent implements OnInit {
addBookForm!: FormGroup;
constructor(private fb: FormBuilder, public dialogRef: MatDialogRef<AddNewBookComponent>, private libraryService: LibraryService) {}
ngOnInit(): void {
this.addBookForm = this.fb.group({
title: ["", Validators.required],
author: ["", Validators.required],
publication_date: ["", Validators.required],
});
}
/**
* Handles the form submission. If the form is valid, it formats the data,
* calls the library service to create the book, and closes the dialog on success.
*/
onSubmit(): void {
console.log("Form submitted:", this.addBookForm.value);
if (this.addBookForm.valid) {
// Ensure date is formatted correctly if needed by the API (e.g., YYYY-MM-DD)
const formattedDate = this.formatDate(this.addBookForm.value.publication_date);
const bookRequest: BookRequest = {
title: this.addBookForm.value.title,
author: this.addBookForm.value.author,
publication_date: formattedDate,
};
const bookData: LibraryBooksCreateRequestParams = {
bookRequest: bookRequest,
};
this.libraryService.libraryBooksCreate(bookData).subscribe({
next: (response) => {
console.log("Book added successfully", response);
this.dialogRef.close(true);
},
error: (error) => {
console.error("Error adding book:", error);
},
});
} else {
this.addBookForm.markAllAsTouched();
}
}
/**
* Closes the dialog without submitting the form.
*/
onCancel(): void {
this.dialogRef.close(); // Close dialog without passing any data
}
/**
* Helper function to format a Date object into 'YYYY-MM-DD' string format.
* @param date - The date to format.
* @returns The formatted date string.
*/
private formatDate(date: Date): string {
const d = new Date(date);
let month = "" + (d.getMonth() + 1);
let day = "" + d.getDate();
const year = d.getFullYear();
if (month.length < 2) month = "0" + month;
if (day.length < 2) day = "0" + day;
return [year, month, day].join("-");
}
}
Poi aggiorna il template HTML (add-new-book.component.html) per includere i campi del form e i pulsanti.
<!-- src/app/modules/library/components/add-new-book/add-new-book.component.html -->
<h2 mat-dialog-title>Add New Book</h2>
<mat-dialog-content>
<form [formGroup]="addBookForm" id="addBookForm">
<!-- Title Field -->
<mat-form-field appearance="outline" class="full-width">
<mat-label>Title</mat-label>
<input matInput formControlName="title" placeholder="Enter book title" required />
<mat-error *ngIf="addBookForm.get('title')?.hasError('required')"> Title is required </mat-error>
</mat-form-field>
<!-- Author Field -->
<mat-form-field appearance="outline" class="full-width">
<mat-label>Author</mat-label>
<input matInput formControlName="author" placeholder="Enter author name" required />
<mat-error *ngIf="addBookForm.get('author')?.hasError('required')"> Author is required </mat-error>
</mat-form-field>
<!-- Publication Date Field -->
<mat-form-field appearance="outline" class="full-width">
<mat-label>Publication Date</mat-label>
<input matInput [matDatepicker]="picker" formControlName="publication_date" placeholder="Choose a date" required />
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
<mat-error *ngIf="addBookForm.get('publication_date')?.hasError('required')"> Publication Date is required </mat-error>
</mat-form-field>
</form>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button (click)="onCancel()">Cancel</button>
<!-- Bind the form submission to the form element's submit event -->
<button mat-raised-button color="primary" type="submit" form="addBookForm" [disabled]="!addBookForm.valid" (click)="onSubmit()">Add Book</button>
</mat-dialog-actions>
Aggiungi un po’ di stile di base ai campi del form:
// src/app/modules/library/components/add-new-book/add-new-book.component.scss
.full-width {
width: 100%;
margin-top: 1rem;
}
/* Ensure mat-dialog-content has enough space */
mat-dialog-content {
padding-top: 20px;
}
Questo è il risultato.

Ora possiamo aggiungere un nuovo libro. Useremo “The Restaurant at the End of the Universe” di “Adams, Douglas” pubblicato il “1 ottobre 1980”.

Quando proviamo a inserire il libro notiamo che qualcosa non va, quindi apriamo il debugger del browser e controlliamo cosa sta succedendo.

L’errore
“Incorrect type. Expected pk value, received str.” questo è l’errore.
L’errore “Incorrect type. Expected pk value, received str.” indica che l’API si aspetta un valore di chiave primaria (pk) per il campo author, ma ha ricevuto una stringa (str). Questo accade perché la richiesta di inserimento del libro si aspetta che l’oggetto author sia referenziato tramite il suo ID univoco e non tramite il nome. Per associare il libro all’autore corretto è necessario inviare l’ID dell’autore esistente nel database.
Per risolvere il problema usiamo il componente autocomplete di angular-material per trovare un Author e restituire il suo id nell’oggetto.
Per prima cosa dobbiamo permettere alla nostra applicazione di filtrare gli autori, quindi modifichiamo il nostro oggetto AuthorViewSet come segue:
from rest_framework import viewsets
from library.models import Author
from library.serializers import AuthorSerializer
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import SearchFilter, OrderingFilter
from library.pagination import LibraryPagination
class AuthorViewSet(viewsets.ModelViewSet):
"""
A viewset for viewing and editing Author instances.
This viewset provides the following features:
- Lists, retrieves, creates, updates, and deletes Author objects.
- Supports filtering by 'first_name', 'last_name', and 'citizenship'.
- Allows searching by 'first_name' and 'last_name'.
- Supports ordering by 'first_name' and 'last_name', with default ordering by 'last_name' then 'first_name'.
- Uses a custom pagination class (LibraryPagination).
Attributes:
queryset (QuerySet): The queryset of Author objects.
serializer_class (Serializer): The serializer class for Author objects.
filter_backends (list): The list of filter backends for filtering, ordering, and searching.
search_fields (list): Fields to enable search functionality.
ordering_fields (list): Fields that can be used for ordering results.
ordering (list): Default ordering for the queryset.
filterset_fields (list): Fields that can be used for filtering results.
pagination_class (Pagination): The pagination class to use for paginating results.
"""
queryset = Author.objects.all()
serializer_class = AuthorSerializer
filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter]
search_fields = ['first_name', 'last_name']
ordering_fields = ['first_name', 'last_name']
ordering = ['last_name', 'first_name']
filterset_fields = ['first_name', 'last_name', 'citizenship']
pagination_class = LibraryPagination
Ricostruiamo il nostro client rest con npm run generate:api.
Usare Mat-Autocomplete
<!-- Author Field -->
<mat-form-field appearance="outline" class="full-width">
<mat-label>Author</mat-label>
<input matInput formControlName="author" placeholder="Enter author name" required [matAutocomplete]="auto" />
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
@for (author of filteredOptions | async; track author.id) {
<mat-option [value]="author"> {{ author.first_name }} {{ author.last_name }} </mat-option>
}
</mat-autocomplete>
<mat-error *ngIf="addBookForm.get('author')?.hasError('required')"> Author is required </mat-error>
</mat-form-field>
Questo codice definisce un campo di form Angular Material per selezionare un autore. Ecco la spiegazione:
<mat-form-field appearance="outline" class="full-width">: crea un campo di input stilizzato che occupa tutta la larghezza del suo contenitore.<mat-label>Author</mat-label>: imposta l’etichetta del campo di input.<input matInput formControlName="author" ...>: collega l’input al form controlauthor, rendendolo parte di un form reattivo. L’attributorequiredgarantisce che il campo debba essere compilato.[matAutocomplete]="auto": collega l’input a un menu a tendina di autocompletamento Material.<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">: definisce il pannello di autocompletamento, usando una funzione di visualizzazione personalizzata (displayFn) per mostrare i valori selezionati.@for (author of filteredOptions | async; track author.id) { ... }: itera (in modo asincrono) sull’elenco filtrato degli autori, usando l’iddi ciascun autore per il tracciamento.<mat-option [value]="author"> ... </mat-option>: mostra ogni autore come opzione, visualizzandone nome e cognome.<mat-error *ngIf="addBookForm.get('author')?.hasError('required')"> ... </mat-error>: mostra un messaggio di errore se il campo autore viene lasciato vuoto.
Questa configurazione offre un modo semplice per selezionare un autore da un elenco filtrato, con validazione e feedback chiaro.
filteredOptions: Observable<Author[]> | undefined;
Questa riga dichiara una proprietà TypeScript chiamata filteredOptions. Questa proprietà può contenere un Observable che emette array di oggetti Author, oppure può essere undefined. Nelle applicazioni Angular una proprietà di questo tipo è comunemente usata per memorizzare i risultati di un’operazione di filtro, ad esempio quando si implementa l’autocompletamento. L’uso di Observable permette alla UI di aggiornarsi in modo reattivo al variare dei dati nel tempo.
ngOnInit(): void {
const authorControl = new FormControl('', Validators.required);
this.addBookForm = this.fb.group({
title: ['', Validators.required],
author: authorControl,
publication_date: ['', Validators.required],
});
this.filteredOptions = authorControl.valueChanges.pipe(
startWith(''),
switchMap((value) => {
if (typeof value === 'string') {
return this._filter(value);
}
return [[]];
})
);
}
Questo codice definisce l’hook del ciclo di vita ngOnInit in un componente Angular. Ecco cosa succede passo dopo passo:
- Inizializzazione del FormControl:
Viene creato un nuovoFormControlchiamatoauthorControlper il campo autore, con un validatore required per garantire che il campo non resti vuoto. - Creazione del Form Group:
Il form groupaddBookFormviene inizializzato usando ilFormBuilderdi Angular (this.fb.group). Contiene tre campi:title: un campo di testo obbligatorio.author: l’authorControlcreato in precedenza.publication_date: un altro campo di testo obbligatorio.
- Filtro di autocompletamento:
L’observablefilteredOptionsviene configurato per fornire le opzioni di autocompletamento filtrate per il campo autore.- Rimane in ascolto delle modifiche di valore di
authorControl. - A ogni modifica parte da una stringa vuota e usa
switchMapper chiamare il metodo_filterse il valore è una stringa. - Se il valore non è una stringa, restituisce un array vuoto.
- Rimane in ascolto delle modifiche di valore di
Punti chiave:
- Questa configurazione è tipica per implementare un input con autocompletamento nei form Angular.
- I validatori garantiscono che i campi obbligatori siano compilati.
- L’uso degli observable permette aggiornamenti reattivi delle opzioni di autocompletamento mentre l’utente digita.
displayFn(author: Author): string {
return author ? author.first_name + ' ' + author.last_name : '';
}
La funzione displayFn riceve in input un oggetto Author e restituisce una stringa. Se author esiste (non è null né undefined), concatena le proprietà first_name e last_name separate da uno spazio, mostrando di fatto il nome completo dell’autore. Se author non viene fornito, restituisce una stringa vuota. Questa funzione è utile per formattare le informazioni sull’autore a scopo di visualizzazione.
private _filter(name: string): Observable<Author[]> {
const params: LibraryAuthorsListRequestParams = {
search: name,
pageSize: 3,
};
return this.libraryService
.libraryAuthorsList(params)
.pipe(
map((data) => (data && Array.isArray(data.results) ? data.results : []))
);
}
Il metodo _filter è una funzione privata che riceve un parametro stringa name e restituisce un Observable di un array di oggetti Author. Ecco come funziona:
- Preparazione dei parametri:
Crea un oggettoparamsdi tipoLibraryAuthorsListRequestParams, impostando la proprietàsearchsul valorenamefornito e limitandopageSizea 3. Questo significa che il metodo richiederà al massimo 3 autori che corrispondono al termine di ricerca. - Chiamata al servizio:
ChiamalibraryService.libraryAuthorsList(params), che dovrebbe restituire un observable contenente i risultati della ricerca degli autori. - Mappatura del risultato:
Il metodo usa gli operatoripipeemapdi RxJS per elaborare la risposta. Controlla se la risposta (data) esiste e sedata.resultsè un array. In tal caso restituiscedata.results, altrimenti restituisce un array vuoto.
Punti chiave:
- Questo metodo è utile per implementare funzionalità come l’autocompletamento o i suggerimenti di ricerca, dove si vuole recuperare un piccolo elenco filtrato di autori in base all’input dell’utente.
- L’uso degli observable permette al metodo di gestire flussi di dati asincroni, cosa molto comune nelle applicazioni Angular.
Possibili insidie:
- Se
libraryService.libraryAuthorsListnon restituisce un oggetto con un arrayresults, il metodo restituirà sempre un array vuoto. - Il metodo è privato, quindi può essere usato solo all’interno della classe in cui è definito.
Ecco il codice completo:
<!-- src/app/modules/library/components/add-new-book/add-new-book.component.html -->
<h2 mat-dialog-title>Add New Book</h2>
<mat-dialog-content>
<form [formGroup]="addBookForm" id="addBookForm">
<!-- Title Field -->
<mat-form-field appearance="outline" class="full-width">
<mat-label>Title</mat-label>
<input matInput formControlName="title" placeholder="Enter book title" required />
<mat-error *ngIf="addBookForm.get('title')?.hasError('required')"> Title is required </mat-error>
</mat-form-field>
<!-- Author Field -->
<mat-form-field appearance="outline" class="full-width">
<mat-label>Author</mat-label>
<input matInput formControlName="author" placeholder="Enter author name" required [matAutocomplete]="auto" />
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
@for (author of filteredOptions | async; track author.id) {
<mat-option [value]="author"> {{ author.first_name }} {{ author.last_name }} </mat-option>
}
</mat-autocomplete>
<mat-error *ngIf="addBookForm.get('author')?.hasError('required')"> Author is required </mat-error>
</mat-form-field>
<!-- Publication Date Field -->
<mat-form-field appearance="outline" class="full-width">
<mat-label>Publication Date</mat-label>
<input matInput [matDatepicker]="picker" formControlName="publication_date" placeholder="Choose a date" required />
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
<mat-error *ngIf="addBookForm.get('publication_date')?.hasError('required')"> Publication Date is required </mat-error>
</mat-form-field>
</form>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button (click)="onCancel()">Cancel</button>
<!-- Bind the form submission to the form element's submit event -->
<button mat-raised-button color="primary" type="submit" form="addBookForm" [disabled]="!addBookForm.valid" (click)="onSubmit()">Add Book</button>
</mat-dialog-actions>
// src/app/modules/library/components/add-new-book/add-new-book.component.ts
import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormControl } from "@angular/forms";
import { MatDialogRef } from "@angular/material/dialog";
import { Author, BookRequest, LibraryAuthorsListRequestParams, LibraryBooksCreateRequestParams, LibraryService } from "../../../core/api/v1"; // Adjust path as needed
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatInputModule } from "@angular/material/input";
import { MatButtonModule } from "@angular/material/button";
import { MatDatepickerModule } from "@angular/material/datepicker";
import { MatAutocompleteModule } from "@angular/material/autocomplete";
import { DateAdapter, MAT_DATE_FORMATS, MAT_NATIVE_DATE_FORMATS, MatNativeDateModule, NativeDateAdapter } from "@angular/material/core";
import { CommonModule } from "@angular/common";
import { MatDialogModule, MatDialogTitle, MatDialogContent, MatDialogActions } from "@angular/material/dialog";
import { filter, map, Observable, startWith, switchMap } from "rxjs";
@Component({
selector: "app-add-new-book",
imports: [
CommonModule,
ReactiveFormsModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
MatDatepickerModule,
MatNativeDateModule,
MatDialogModule,
MatDialogTitle,
MatDialogContent,
MatDialogActions,
MatAutocompleteModule,
],
providers: [
{ provide: DateAdapter, useClass: NativeDateAdapter },
{ provide: MAT_DATE_FORMATS, useValue: MAT_NATIVE_DATE_FORMATS },
],
templateUrl: "./add-new-book.component.html",
styleUrls: ["./add-new-book.component.scss"],
})
/**
* Component for adding a new book to the library.
*
* This component provides a form for entering book details, including title, author, and publication date.
* It features an autocomplete input for selecting authors, which fetches matching authors from the backend as the user types.
* Upon form submission, the component validates the input, formats the data as required by the API, and sends a request to create the new book.
* The dialog is closed upon successful creation or cancellation.
*
* @remarks
* - Uses Angular Reactive Forms for form handling and validation.
* - Integrates with the `LibraryService` to fetch authors and create books.
* - Utilizes Angular Material Dialog for modal functionality.
* - Implements an autocomplete feature for author selection.
*
* @see LibraryService
*/
export class AddNewBookComponent implements OnInit {
addBookForm!: FormGroup;
filteredOptions: Observable<Author[]> | undefined;
/**
* Initializes a new instance of the AddNewBookComponent.
*
* @param fb - The FormBuilder service used to create and manage reactive forms.
* @param dialogRef - Reference to the dialog opened for adding a new book.
* @param libraryService - Service for interacting with the library's data and operations.
*/
constructor(private fb: FormBuilder, public dialogRef: MatDialogRef<AddNewBookComponent>, private libraryService: LibraryService) {}
/**
* Initializes the add book form and sets up the filtered options for the author autocomplete.
*
* - Creates a reactive form group with controls for title, author, and publication date.
* - Sets up an observable (`filteredOptions`) that listens to changes in the author input,
* and filters the available author options accordingly.
* - Uses `startWith` to initialize the filter and `switchMap` to handle asynchronous filtering logic.
*/
ngOnInit(): void {
const authorControl = new FormControl("", Validators.required);
this.addBookForm = this.fb.group({
title: ["", Validators.required],
author: authorControl,
publication_date: ["", Validators.required],
});
this.filteredOptions = authorControl.valueChanges.pipe(
startWith(""),
switchMap((value) => {
if (typeof value === "string") {
return this._filter(value);
}
return [[]];
})
);
}
/**
* Formats an Author object into a display string.
*
* @param author - The Author object to format.
* @returns The author's full name as a string, or an empty string if the author or first name is not provided.
*/
displayFn(author: Author): string {
return author ? author.first_name + " " + author.last_name : "";
}
/**
* Filters authors based on the provided name by querying the library service.
*
* @param name - The search string used to filter authors.
* @returns An Observable emitting an array of Author objects matching the search criteria.
*/
private _filter(name: string): Observable<Author[]> {
const params: LibraryAuthorsListRequestParams = {
search: name,
pageSize: 3,
};
return this.libraryService.libraryAuthorsList(params).pipe(map((data) => (data && Array.isArray(data.results) ? data.results : [])));
}
/**
* Handles the form submission. If the form is valid, it formats the data,
* calls the library service to create the book, and closes the dialog on success.
*/
onSubmit(): void {
console.log("Form submitted:", this.addBookForm.value);
if (this.addBookForm.valid) {
// Ensure dte is formatted correctly if needed by the API (e.g., YYYY-MM-DD)
const formattedDate = this.formatDate(this.addBookForm.value.publication_date);
const bookRequest: BookRequest = {
title: this.addBookForm.value.title,
author: this.addBookForm.value.author.id,
publication_date: formattedDate,
};
const bookData: LibraryBooksCreateRequestParams = {
bookRequest: bookRequest,
};
this.libraryService.libraryBooksCreate(bookData).subscribe({
next: (response) => {
console.log("Book added successfully", response);
this.dialogRef.close(true);
},
error: (error) => {
console.error("Error adding book:", error);
},
});
} else {
this.addBookForm.markAllAsTouched();
}
}
/**
* Closes the dialog without submitting the form.
*/
onCancel(): void {
this.dialogRef.close(); // Close dialog without passing any data
}
/**
* Helper function to format a Date object into 'YYYY-MM-DD' string format.
* @param date - The date to format.
* @returns The formatted date string.
*/
private formatDate(date: Date): string {
const d = new Date(date);
let month = "" + (d.getMonth() + 1);
let day = "" + d.getDate();
const year = d.getFullYear();
if (month.length < 2) month = "0" + month;
if (day.length < 2) day = "0" + day;
return [year, month, day].join("-");
}
}

Ora proviamo a inserire il nostro libro.
Possiamo vedere che il libro è stato aggiunto correttamente, ma ci sono ancora due problemi da risolvere:
- Non c’è nessun messaggio che ci permetta di capire se il libro è stato inserito correttamente.
- L’elenco dei libri non si aggiorna al termine dell’inserimento.
Aggiungere un avviso di notifica
Aggiungiamo un nuovo componente LibraryNotificationComponent:
# ng generate component modules/library/components/LibraryNotification
CREATE src/app/modules/library/components/library-notification/library-notification.component.scss (0 bytes)
CREATE src/app/modules/library/components/library-notification/library-notification.component.html (35 bytes)
CREATE src/app/modules/library/components/library-notification/library-notification.component.spec.ts (684 bytes)
CREATE src/app/modules/library/components/library-notification/library-notification.component.ts (270 bytes)
Ora creiamo una nuova interfaccia per gestire i messaggi di notifica.
# ng generate interface modules/library/models/LibraryNotification
CREATE src/app/modules/library/models/library-notification.ts (41 bytes)
Aggiorna l’interfaccia LibraryNotification come segue:
export interface LibraryNotification {
message: string;
type: "success" | "error" | "info" | "warning";
duration?: number; // Duration in milliseconds
}
Genera un nuovo servizio LibraryNotificationService:
# ng generate service modules/library/services/LibraryNotification
CREATE src/app/modules/library/services/library-notification.service.spec.ts (423 bytes)
CREATE src/app/modules/library/services/library-notification.service.ts (148 bytes)
Ora modifica il servizio come segue:
import { BehaviorSubject, Observable } from "rxjs";
import { Injectable } from "@angular/core";
import { LibraryNotification } from "../models/library-notification";
@Injectable({
providedIn: "root",
})
/**
* Service for managing and emitting library notifications.
*
* This service uses a BehaviorSubject to hold and update a list of LibraryNotification objects.
* It provides methods to add, retrieve, and remove notifications, and exposes an observable
* stream of notifications for components to subscribe to.
*/
export class LibraryNotificationService {
private notification_list$: BehaviorSubject<LibraryNotification[]> = new BehaviorSubject<LibraryNotification[]>([]);
notification_list: Observable<LibraryNotification[]> = this.notification_list$.asObservable();
constructor() {}
/**
* Adds a new notification to the list and emits the updated array.
* @param notification - The notification to add.
*/
notify(notification: LibraryNotification) {
// console.log('Notification:', notification);
this.notification_list$.next([...this.notification_list$.value, notification]);
}
/**
* Retrieves the first notification from the notification stream.
* @returns {LibraryNotification} The first notification in the stream.
*/
getNotification(): LibraryNotification {
return this.notification_list$.value[0];
}
/**
* Removes a notification from the list and emits the updated array.
* @param notification - The notification to remove.
*/
removeNotification(notification: LibraryNotification) {
const notifications = this.notification_list$.value.filter((n) => n !== notification);
this.notification_list$.next(notifications);
}
}
Il codice selezionato è un servizio scritto in TypeScript per un’applicazione Angular. È pensato per gestire ed emettere notifiche all’interno di una library. Analizziamo il codice sezione per sezione:
1. Import:
import { BehaviorSubject, Observable } from "rxjs";
import { Injectable } from "@angular/core";
import { LibraryNotification } from "../models/library-notification";
BehaviorSubjecteObservabledarxjs: fanno parte della libreria Reactive Extensions for JavaScript (RxJS), ampiamente usata in Angular per gestire flussi di dati asincroni.BehaviorSubjectè un tipo diObservableche mantiene un valore corrente e lo emette ai nuovi sottoscrittori.Injectableda@angular/core: questo decoratore contrassegna la classe come un servizio che può essere iniettato in altri componenti o servizi tramite il sistema di dependency injection di Angular.LibraryNotificationda'../models/library-notification': importa la definizione di un tipo o di una classe personalizzata per un oggetto notifica. Si presume cheLibraryNotificationsia definito in un file separato e abbia proprietà rilevanti per la notifica (ad esempio message, type, ecc.).
2. Decoratore @Injectable:
@Injectable({
providedIn: 'root',
})
@Injectable: come detto sopra, contrassegna la classe come disponibile per la dependency injection.providedIn: 'root': configura il servizio come singleton, cioè Angular creerà una sola istanza di questo servizio per l’intera applicazione. È disponibile a livello di injector root.
3. Definizione della classe: LibraryNotificationService
export class LibraryNotificationService {
// ... class members ...
}
- Definisce la classe del servizio. La parola chiave
exportla rende disponibile per l’uso in altre parti dell’applicazione.
4. notification_list$ (BehaviorSubject):
private notification_list$: BehaviorSubject<LibraryNotification[]> =
new BehaviorSubject<LibraryNotification[]>([]);
private notification_list$: BehaviorSubject<LibraryNotification[]>: dichiara unBehaviorSubjectprivato chiamatonotification_list$.BehaviorSubject<LibraryNotification[]>: è progettato per contenere un array di oggettiLibraryNotification. Il suffisso$è una convenzione per indicare che si tratta di un Observable.new BehaviorSubject<LibraryNotification[]>([]): viene inizializzato con un array vuoto ([]), cioè il valore iniziale del flusso di notifiche è un elenco vuoto.
5. notification_list (Observable):
notification_list: Observable<LibraryNotification[]> = this.notification$.asObservable();
notification_list: Observable<LibraryNotification[]>: dichiara unObservablepubblico chiamatonotification_list.this.notification_list$.asObservable(): viene creato chiamando.asObservable()sul BehaviorSubjectnotification_list$. Restituisce un Observable di sola lettura a cui i componenti possono sottoscriversi. I sottoscrittori riceveranno aggiornamenti ogni volta che il BehaviorSubjectnotification_list$emette un nuovo valore. Aspetto fondamentale: i componenti non possono chiamare direttamente.next()su questoObservableper emettere nuovi valori; solo il servizio può farlo tramite il BehaviorSubjectnotification_list$.
6. constructor():
constructor() {}
- È il costruttore del servizio. Al momento è vuoto, ma qui potresti iniettare altri servizi se questo ne avesse bisogno.
7. Metodo notify():
notify(notification: LibraryNotification) {
// console.log('Notification:', notification);
this.notification_list$.next([...this.notification_list$.value, notification]);
}
notify(notification: LibraryNotification): questo metodo serve ad aggiungere una nuova notifica al flusso.this.notification_list$.next([...this.notification_list$.value, notification]): è la logica centrale per emettere una nuova notifica.this.notification_list$.value: recupera dalBehaviorSubjectl’array corrente di notifiche.[...this.notification_list$.value, notification]: usa lo spread operator (...) per creare un nuovo array che contiene tutte le notifiche esistenti più la nuovanotificationaggiunta in fondo. Importante: questo crea un nuovo array, aspetto fondamentale per il change detection di Angular. Se modificassi direttamente l’array esistente, Angular potrebbe non rilevare il cambiamento e non aggiornare la UI.this.notification_list$.next(...): emette il nuovo array a tutti i sottoscrittori dell’Observablenotification_list.
8. Metodo getNotification():
getNotification(): LibraryNotification {
return this.notification_list$.value[0];
}
getNotification(): LibraryNotification: questo metodo recupera la prima notifica dall’array corrente di notifiche.return this.notification_list$.value[0]: accede al primo elemento (indice 0) dell’arraynotification_list$.valuee lo restituisce.- Importante: questo metodo ha un potenziale problema: se l’array
notification_list$.valueè vuoto, l’accesso all’indice 0 restituisceundefined. Un’implementazione più sicura dovrebbe verificare che l’array non sia vuoto prima di accedere al primo elemento.
9. Metodo removeNotification():
removeNotification(notification: LibraryNotification) {
const notifications = this.notification$.value.filter(
(n) => n !== notification
);
this.notification_list$.next(notifications);
}
removeNotification(notification: LibraryNotification): questo metodo rimuove una specifica notifica dal flusso.this.notification_list$.value.filter((n) => n !== notification): usa il metodofilterper creare un nuovo array contenente solo le notifiche che non sono uguali allanotificationda rimuovere. Per il confronto usa l’uguaglianza stretta (!==).this.notification_list$.next(notifications): emette il nuovo array filtrato a tutti i sottoscrittori dell’Observablenotification.
Concetti chiave e possibili miglioramenti:
- Immutabilità: il servizio usa correttamente operazioni immutabili (spread operator e
filter) per creare nuovi array quando aggiunge o rimuove notifiche. Questo è importante per il change detection di Angular e aiuta a evitare effetti collaterali inattesi. - RxJS: l’uso di
BehaviorSubjecteObservablepermette un approccio reattivo alla gestione delle notifiche. I componenti possono sottoscriversi all’Observablenotificatione ricevere automaticamente gli aggiornamenti ogni volta che l’elenco cambia. - Gestione degli errori: il metodo
getNotification()dovrebbe gestire il caso in cui l’array di notifiche sia vuoto. Valuta di restituireundefinedo di lanciare un errore. - ID delle notifiche: per una gestione più robusta delle notifiche, soprattutto in fase di rimozione, valuta di aggiungere un ID univoco a ogni oggetto
LibraryNotification. Questo permetterebbe di rimuovere notifiche specifiche in base al loro ID, invece di affidarsi all’uguaglianza tra oggetti, che può essere problematica. - Alternative a
BehaviorSubject: a seconda dei requisiti, unSubjecto unReplaySubjectpotrebbe essere più appropriato di unBehaviorSubject. UnSubjectnon mantiene un valore corrente, mentre unReplaySubjectpuò riemettere un certo numero di emissioni passate ai nuovi sottoscrittori.
Ora aggiorniamo il componente LibraryNotification come segue:
import { Component, OnDestroy, OnInit } from "@angular/core";
import { LibraryNotificationService } from "../../services/library-notification.service";
import { LibraryNotification } from "../../models/library-notification";
import { Subject, takeUntil } from "rxjs";
import { NgClass, NgIf } from "@angular/common";
import { MatIconModule } from "@angular/material/icon";
import { MatDividerModule } from "@angular/material/divider";
import { MatButtonModule } from "@angular/material/button";
import { MatProgressBarModule } from "@angular/material/progress-bar";
@Component({
selector: "app-library-notification",
imports: [NgIf, NgClass, MatIconModule, MatDividerModule, MatButtonModule, MatProgressBarModule],
templateUrl: "./library-notification.component.html",
styleUrl: "./library-notification.component.scss",
})
/**
* `LibraryNotificationComponent` is responsible for displaying and managing library notifications.
* It subscribes to the `LibraryNotificationService` to receive notifications and displays them to the user.
* The component automatically removes notifications after a specified duration.
* It also provides a method to manually close notifications.
*
* Implements `OnInit` and `OnDestroy` lifecycle hooks for initialization and cleanup.
*/
export class LibraryNotificationComponent implements OnInit, OnDestroy {
/**
* The `notification` property holds the current notification object.
* It is initialized to null, indicating that there is no notification by default.
*
* @type {LibraryNotification | undefined}
*/
notification: LibraryNotification | undefined;
private destroyStream$ = new Subject<void>();
constructor(private readonly libraryNotificationService: LibraryNotificationService) {}
/**
* The `ngOnInit` lifecycle hook is called after the component has been initialized.
* It is used to perform any necessary initialization tasks, such as subscribing
* to services or fetching data.
*
* @returns {void}
*/
ngOnInit(): void {
console.log("LibraryNotificationComponent initialized");
this.events();
}
/**
* @description This method subscribes to the notification stream from the library notification service.
* When notifications are received, it updates the component's notification property and sets a timeout to remove the notification after its specified duration.
* If there are no notifications, it clears the component's notification property.
* The subscription is automatically unsubscribed when the component is destroyed.
* @async
* @returns {Promise<void>}
*/
async events() {
this.libraryNotificationService.notification_list.pipe(takeUntil(this.destroyStream$)).subscribe(async (notifications) => {
if (notifications.length > 0) {
const notification = this.libraryNotificationService.getNotification();
this.notification = notification;
if (this.notification) {
await new Promise((resolve) =>
setTimeout(() => {
this.libraryNotificationService.removeNotification(notification);
resolve(undefined);
}, notification.duration)
);
}
} else {
this.notification = undefined;
}
});
}
/**
* Closes the current notification by removing it from the library notification service.
* This function checks if a notification exists and then calls the service to remove it.
*/
closeNotification() {
if (this.notification) {
this.libraryNotificationService.removeNotification(this.notification);
}
}
/**
* Lifecycle hook that is called when the component is destroyed.
* It completes the `destroyStream$` Subject, signaling all subscribers to unsubscribe.
*/
ngOnDestroy() {
this.destroyStream$.complete();
}
}
Spiegazione:
- Import: il codice importa i moduli necessari da Angular core, RxJS, Angular common e Angular Material. Questi moduli offrono le funzionalità per creare componenti, gestire operazioni asincrone e usare elementi UI predefiniti.
- Decoratore Component: il decoratore
@Componentserve a definire i metadati del componente, come il selettore, l’URL del template, l’URL dello stile e i moduli richiesti. - Definizione della classe: viene definita la classe
LibraryNotificationComponent, che implementa le interfacceOnIniteOnDestroy. - Proprietà:
notification: questa proprietà contiene l’oggetto notifica corrente di tipoLibraryNotificationoppureundefined.destroyStream$: è unSubjectusato per gestire il ciclo di vita del componente e annullare le sottoscrizioni agli observable quando il componente viene distrutto.
- Costruttore: il costruttore inietta il
LibraryNotificationService, usato per gestire le notifiche della library. - ngOnInit: questo hook del ciclo di vita viene chiamato all’inizializzazione del componente. Chiama il metodo
events()per sottoscriversi al flusso di notifiche. - events(): questo metodo si sottoscrive al flusso
notification_listdelLibraryNotificationService. Quando riceve notifiche, aggiorna la proprietànotificationdel componente e imposta un timeout per rimuovere la notifica dopo la durata specificata. - closeNotification(): questo metodo viene chiamato quando l’utente chiude manualmente la notifica. Rimuove la notifica corrente dal
LibraryNotificationService. - ngOnDestroy: questo hook del ciclo di vita viene chiamato quando il componente viene distrutto. Completa il Subject
destroyStream$, segnalando a tutti i sottoscrittori di annullare la sottoscrizione ed evitando memory leak.
In sostanza, questo componente è pensato per mostrare le notifiche della library, gestirne la durata di visualizzazione e permettere agli utenti di chiuderle manualmente. Sfrutta gli hook del ciclo di vita dei componenti Angular e gli observable RxJS per gestire le operazioni asincrone e lo stato del componente.
<div *ngIf="notification" [ngClass]="notification.type" class="notification">
<div class="notification-header">
<ng-container *ngIf="notification.type === 'error'">
<mat-icon>error</mat-icon>
</ng-container>
<ng-container *ngIf="notification.type === 'success'">
<mat-icon>check_circle</mat-icon>
</ng-container>
<ng-container *ngIf="notification.type === 'info'">
<mat-icon>info</mat-icon>
</ng-container>
<ng-container *ngIf="notification.type === 'warning'">
<mat-icon>warning</mat-icon>
</ng-container>
<span>{{ notification.type }}</span>
<button class="close-btn" mat-icon-button (click)="closeNotification()">
<mat-icon>close</mat-icon>
</button>
</div>
<mat-divider></mat-divider>
<div class="notification-content">
<div [innerHTML]="notification.message"></div>
</div>
<mat-progress-bar mode="indeterminate"></mat-progress-bar>
</div>
Il frammento di codice fornito è un template Angular che mostra un messaggio di notifica all’utente. Ecco la spiegazione:
*ngIf="notification": questa direttiva verifica se l’oggettonotificationesiste. In caso affermativo viene renderizzato l’intero contenitore della notifica, altrimenti resta nascosto.[ngClass]="notification.type": aggiunge dinamicamente una classe CSS aldivprincipale in base alla proprietànotification.type(ad esempio ‘error’, ‘success’, ‘info’, ‘warning’). Questo permette di stilizzare la notifica in base al suo tipo.class="notification": è una classe CSS standard per stilizzare il contenitore della notifica.notification-header: questodivcontiene l’intestazione della notifica, che comprende un’icona, il tipo di notifica e un pulsante di chiusura.*ngIf="notification.type === 'error'"(e analoghi per gli altri tipi): queste direttive renderizzano in modo condizionale unmat-icon(di Angular Material) in base anotification.type. Ogni tipo ha un’icona diversa (error, check_circle, info, warning). : aggiunge uno spazio non separabile per separare visivamente l’icona dal testo del tipo di notifica.<span>{{ notification.type }}</span>: mostra come testo il tipo di notifica.(click)="closeNotification()": collega l’evento click del pulsante di chiusura al metodocloseNotification()del componente, permettendo all’utente di chiudere la notifica.<mat-divider>: è un componente di Angular Material che mostra una linea orizzontale per separare visivamente l’intestazione dal contenuto.notification-content: questodivcontiene il messaggio vero e proprio della notifica.<div>{{ notification.message }}</div>: mostra il messaggio della notifica.<mat-progress-bar mode="indeterminate">: è una barra di avanzamento di Angular Material che indica un processo in corso.mode="indeterminate"significa che la barra mostra un’animazione continua senza un valore specifico.
In sostanza, questo template crea un componente di notifica riutilizzabile, in grado di mostrare diversi tipi di messaggi con stili e icone appropriati. L’oggetto notification contiene probabilmente proprietà come type (ad esempio ‘error’, ‘success’) e message (il testo da mostrare). Il metodo closeNotification() si occupa di rimuovere l’oggetto notification, nascondendo così la notifica.
Infine aggiorniamo style.scss:
@use "@angular/material" as mat;
:root {
@include mat.divider-overrides(
(
color: white,
)
);
@include mat.progress-bar-overrides(
(
active-indicator-color: rgb(188, 180, 180),
track-color: white,
)
);
}
html,
body {
height: 100%;
}
body {
margin: 0;
font-family: Roboto, "Helvetica Neue", sans-serif;
} /* You can add global styles to this file, and also import other style files */
h1 {
color: #333;
text-align: center;
}
a {
color: red;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
a:visited {
color: red;
}
.book {
background-color: #fff;
border: 1px solid #ddd;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
margin: 10px;
padding: 10px;
}
.not_found {
color: #fff;
background-color: rgba(255, 0, 0, 0.65);
font-style: italic;
text-align: center;
}
.library {
display: block;
justify-content: center;
align-items: left;
width: 1200px;
margin: 0 auto;
border: #333 solid 1px;
border-radius: 5px;
padding: 20px;
background-color: #f9f9f9;
}
.library h2 {
display: inline-block;
text-align: left;
color: #333;
width: 200px;
}
.search-form-field {
float: right;
width: 250px;
}
.library-footer {
margin: 20px 0 0 0;
width: 100%;
text-align: right;
}
.full-width {
width: 100%;
margin-top: 1rem;
}
/* Ensure mat-dialog-content has enough space */
mat-dialog-content {
padding-top: 20px;
}
.notification {
position: fixed;
bottom: 1em;
right: 1em;
width: 300px;
padding: 20px;
background-color: #f44336;
color: white;
z-index: 100000;
border-radius: 10px;
border: 1px solid black;
box-shadow: 0 2px 4px 0x0c0c0c85;
transition: opacity 0.3s ease-in-out;
}
.notification.success {
background-color: #4caf50;
}
.notification.error {
background-color: #f44336;
}
.notification.info {
background-color: #2196f3;
}
.notification.warning {
background-color: #ffaa29;
}
.notification-header {
font-weight: bold;
font-size: 1.2em;
display: flex;
height: 30px;
text-shadow: 1px 1px 1px #0c0c0c85;
}
.notification-header .close-btn {
top: 5px;
right: 5px;
cursor: pointer;
position: absolute;
color: white;
}
.notification-header .close-btn:hover {
color: white;
}
.notification-content {
margin: 1em 0;
min-height: 50px;
text-shadow: 1px 1px 1px #0c0c0c85;
}
Infine dobbiamo aggiungere <app-library-notification></app-library-notification> nel template app.component.html:
<h1>{{ title }}</h1>
<div class="library">
<app-library></app-library>
<router-outlet></router-outlet>
</div>
<app-library-notification></app-library-notification>
Ora possiamo aggiornare il metodo onSubmit() in AddNewBookComponent per gestire le notifiche:
/**
* Handles the form submission. If the form is valid, it formats the data,
* calls the library service to create the book, and closes the dialog on success.
*/
onSubmit(): void {
console.log('Form submitted:', this.addBookForm.value);
if (this.addBookForm.valid) {
// Ensure date is formatted correctly if needed by the API (e.g., YYYY-MM-DD)
const formattedDate = this.formatDate(
this.addBookForm.value.publication_date
);
const bookRequest: BookRequest = {
title: this.addBookForm.value.title,
author: this.addBookForm.value.author.id,
publication_date: formattedDate,
};
const bookData: LibraryBooksCreateRequestParams = {
bookRequest: bookRequest,
};
this.libraryService.libraryBooksCreate(bookData).subscribe({
next: (response) => {
console.log('Book added successfully', response);
this.libraryNotificationService.notify({
message: 'Book added successfully',
type: 'success',
duration: 3000,
});
this.dialogRef.close(true);
},
error: (error) => {
const errorMessage = error?.error || {};
let errorMessageString = '<br><br>';
for (const key in errorMessage) {
errorMessageString += `<strong>${key}</strong>: ${errorMessage[key][0]}<br><br>`;
}
// Handle error response
this.libraryNotificationService.notify({
message: 'Error adding book \n' + errorMessageString,
type: 'error',
duration: 3000,
});
},
});
} else {
this.addBookForm.markAllAsTouched();
}
}
Spiegazione:
this.libraryService.libraryBooksCreate(bookData).subscribe({ ... });- Questa riga avvia il processo di creazione di un nuovo libro.
this.libraryService.libraryBooksCreate(bookData): questa parte chiama un metodo (libraryBooksCreate) su un oggettolibraryService, passando come argomentobookData, che presumibilmente contiene le informazioni necessarie a creare il nuovo libro (titolo, autore, ecc.). Il metodo restituisce probabilmente un Observable (di RxJS)..subscribe({...}): è la parte cruciale che gestisce la natura asincrona della chiamata API.subscribeserve ad ascoltare i risultati del metodolibraryBooksCreate(l’Observable) e accetta un oggetto con le funzioninextederror.
next: (response) => { ... }- Questa funzione viene eseguita se la chiamata API ha successo.
console.log('Book added successfully', response);: scrive nella console un messaggio di successo insieme ai dati di risposta dell’API.this.libraryNotificationService.notify({ ... });: chiama il metodonotifydilibraryNotificationServiceper mostrare un messaggio di successo all’utente.message: il messaggio da mostrare (“Book added successfully”).type: il tipo di notifica (“success”). Può determinare lo stile della notifica (ad esempio il colore verde).duration: per quanto tempo la notifica deve restare visibile (3000 millisecondi = 3 secondi).
this.dialogRef.close(true);: chiude la finestra di dialogo o modale, passandotrueper indicare che l’operazione è riuscita.
error: (error) => { ... }- Questa funzione viene eseguita se la chiamata API fallisce.
const errorMessage = error?.error || {};: estrae il messaggio di errore dall’oggettoerror. Usa l’optional chaining (?.) per accedere in modo sicuro alla proprietàerrore|| {}per fornire un oggetto vuoto di default seerror?.errorè null o undefined.- Il codice poi itera sulle chiavi dell’oggetto
errorMessagee costruisce una stringa HTML (errorMessageString) per mostrare i messaggi di errore in modo formattato. Presuppone che il messaggio di errore sia un oggetto in cui ogni chiave rappresenta un campo con un errore e il valore sia un array contenente il messaggio di errore per quel campo. this.libraryNotificationService.notify({ ... });: mostra una notifica di errore all’utente.message: il messaggio di errore da mostrare. Include laerrorMessageStringformattata per mostrare informazioni di errore dettagliate.type: il tipo di notifica (“error”). Può determinare lo stile della notifica (ad esempio il colore rosso).duration: per quanto tempo la notifica deve restare visibile (3000 millisecondi).
In sintesi:
Il codice gestisce la creazione asincrona di un libro tramite un’API. Mostra una notifica di successo se il libro viene creato correttamente e una notifica di errore se la creazione fallisce, includendo i messaggi di errore dettagliati forniti dall’API. Il dialog viene chiuso solo in caso di successo.
Ora possiamo aggiungere il libro Hunger Games di Suzanne Collins, pubblicato il 14 settembre 2008.

Abbiamo ottenuto correttamente un errore dovuto al fatto che l’autore non esiste ancora nel nostro database. Questa funzionalità verrà affrontata più avanti; intanto abbiamo testato con successo la nostra notifica.
Aggiornare l’elenco dei libri
Generiamo un nuovo servizio:
# ng generate service modules/library/services/LibraryBooksListUpdate
CREATE src/app/modules/library/services/library-books-list-update.service.spec.ts (440 bytes)
CREATE src/app/modules/library/services/library-books-list-update.service.ts (151 bytes)
Aggiungiamo il seguente codice:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class LibraryBooksListUpdateService {
private booksListUpdate: Subject<void> = new Subject<void>();
booksListUpdate$ = this.booksListUpdate.asObservable();
constructor() {}
updateBooksList() {
this.booksListUpdate.next();
}
}
Spiegazione:
- Import:
Injectableda@angular/core: questo decoratore contrassegna la classe come una classe a cui possono essere iniettate dipendenze.Subjectdarxjs: unSubjectè un tipo speciale di Observable che permette di inviare i valori in multicast a molti Observer. Qui viene usato per segnalare gli aggiornamenti dell’elenco dei libri.
- Decoratore
@Injectable:@Injectable({ providedIn: 'root' }): rende il servizio disponibile in tutta l’applicazione. L’impostazionerootsignifica che Angular creerà una singola istanza condivisa del servizio.
- Classe
LibraryBooksListUpdateService:- Questo servizio è pensato per gestire gli aggiornamenti di un elenco di libri della library.
private booksListUpdate: Subject<void> = new Subject<void>();:booksListUpdateè unSubjectprivato. È di tipovoidperché con l’aggiornamento non inviamo alcun dato specifico, ma solo la notifica che un aggiornamento è avvenuto.Subject<void>: un Subject che non trasporta dati.private: garantisce che solo il servizio stesso possa attivare direttamente gli aggiornamenti.
booksListUpdate$ = this.booksListUpdate.asObservable();:booksListUpdate$è un Observable pubblico a cui i componenti possono sottoscriversi..asObservable(): converte ilSubjectin unObservable, impedendo ai componenti esterni di chiamare direttamentenext()sul Subject (cosa che permetterebbe loro di attivare gli aggiornamenti). Questo rafforza il principio per cui solo il servizio stesso deve avviare gli aggiornamenti.
constructor() {}: un costruttore vuoto. In questo esempio non vengono iniettate dipendenze.updateBooksList() { this.booksListUpdate.next(); }:- Questo metodo è l’API pubblica per attivare un aggiornamento dell’elenco dei libri.
this.booksListUpdate.next(): emette una notifica a tutti i sottoscrittori dell’ObservablebooksListUpdate$, segnalando che l’elenco dei libri è stato aggiornato.
In sostanza, questo servizio offre un modo centralizzato per notificare ai componenti che l’elenco dei libri della library è cambiato, permettendo loro di aggiornare i propri dati.
Aggiorna il metodo ngInit() in BooksListComponent:
ngOnInit(): void {
this.getBooks();
this.searchSubject.pipe(debounceTime(300)).subscribe((searchText) => {
this.searchText = searchText;
this.pageIndex = 0;
this.getBooks();
});
this.booksListUpdateService.booksListUpdate$.subscribe(() => {
this.searchText = '';
this.pageIndex = 0;
this.getBooks();
});
}
this.booksListUpdateService.booksListUpdate$.subscribe(() => { ... });: si sottoscrive all’observablebooksListUpdate$di un servizio chiamatobooksListUpdateService.() => { ... }: è la funzione di callback che viene eseguita quando l’observablebooksListUpdate$emette un valore.this.searchText = '';: svuotasearchText, presumibilmente per azzerare la ricerca.this.pageIndex = 0;: riportapageIndexa 0.this.getBooks();: richiama il metodogetBooksper aggiornare l’elenco dei libri, ad esempio dopo un aggiornamento o una modifica.
In sintesi, il metodo ngOnInit inizializza il componente recuperando i libri, configurando una ricerca con debounce e sottoscrivendosi a un servizio di aggiornamento dell’elenco dei libri per aggiornarlo quando avvengono modifiche.
In LibraryComponent aggiorna:
openAddBookDialog(): void {
const dialogRef = this.dialog.open(AddNewBookComponent, {
width: '700px',
});
dialogRef.afterClosed().subscribe((result) => {
console.log('The dialog was closed');
if (result) {
this.booksListUpdateService.updateBooksList();
console.log('Dialog result:', result);
}
});
}
La funzione openAddBookDialog si occupa di aprire una finestra di dialogo (probabilmente modale) che permette all’utente di aggiungere un nuovo libro. Analizziamola passo dopo passo:
- Apertura del dialog:
this.dialog.open(AddNewBookComponent, { width: '700px' });- Questa riga usa il servizio
dialog(presumibilmente di Angular Material o di una libreria UI simile) per aprire una finestra di dialogo. AddNewBookComponentè il componente che verrà mostrato all’interno del dialog. Probabilmente contiene il form e la logica per aggiungere un nuovo libro.{ width: '700px' }è un oggetto di configurazione che imposta la larghezza del dialog a 700 pixel.- Il metodo
dialog.openrestituisce un riferimento al dialog aperto (dialogRef).
- Questa riga usa il servizio
- Gestione della chiusura del dialog:
dialogRef.afterClosed().subscribe((result) => { ... });- Imposta una sottoscrizione all’observable
afterClosed()del riferimento al dialog. Questo observable emette un valore quando il dialog viene chiuso (inviando il form o annullando). - Il parametro
resultnella callback disubscribecontiene i dati restituiti dal dialog alla chiusura. Potrebbero essere i dati del nuovo libro, oppureundefinedse il dialog è stato annullato.
- Imposta una sottoscrizione all’observable
- Logica successiva alla chiusura:
console.log('The dialog was closed');- Un semplice log in console per indicare che il dialog è stato chiuso.
if (result) { ... }- Verifica che
resultsia truthy (cioè nonnull,undefinedo un oggetto vuoto). Questo implica che l’utente ha probabilmente inviato il form con successo.
- Verifica che
this.booksListUpdateService.updateBooksList();- Se esiste un
result, questa riga chiama un metodo dibooksListUpdateServiceper aggiornare l’elenco dei libri. Probabilmente recupera l’elenco aggiornato dal backend oppure aggiorna l’elenco locale con il libro appena aggiunto.
- Se esiste un
console.log('Dialog result:', result);- Scrive il
resultin console, permettendo di ispezionare i dati restituiti dal dialog.
- Scrive il
In sostanza, questa funzione apre un dialog e, quando il dialog viene chiuso, aggiorna l’elenco dei libri se ha restituito un risultato valido.
Aggiungere un nuovo autore
Ora aggiorniamo il nostro AddNewBookComponent per gestire l’inserimento di nuovi autori. Creiamo un nuovo componente chiamato AddNewAuthorComponent:
# ng generate component modules/library/components/AddNewAuthor
CREATE src/app/modules/library/components/add-new-author/add-new-author.component.scss (0 bytes)
CREATE src/app/modules/library/components/add-new-author/add-new-author.component.html (29 bytes)
CREATE src/app/modules/library/components/add-new-author/add-new-author.component.spec.ts (636 bytes)
CREATE src/app/modules/library/components/add-new-author/add-new-author.component.ts (245 bytes)
Aggiorna add-new-author.component.html come segue:
<mat-card class="add-author-card">
<form class="add-author-form" [formGroup]="addAuthorForm">
<mat-card-header>
<mat-card-title>Add New Author</mat-card-title>
</mat-card-header>
<mat-card-content>
<mat-form-field appearance="outline" class="full-width">
<mat-label>First Name</mat-label>
<input formControlName="first_name" matInput placeholder="First Name" required />
<mat-error *ngIf="addAuthorForm.get('first_name')?.hasError('required')"> First Name is required </mat-error>
</mat-form-field>
<mat-form-field appearance="outline" class="full-width">
<mat-label>Last Name</mat-label>
<input formControlName="last_name" matInput placeholder="Last Name" required />
<mat-error *ngIf="addAuthorForm.get('last_name')?.hasError('required')"> Last Name is required </mat-error>
</mat-form-field>
<mat-form-field appearance="outline" class="full-width">
<mat-label>Cityzenship</mat-label>
<input formControlName="citizenship" matInput placeholder="Cityzenship" required />
<mat-error *ngIf="addAuthorForm.get('citizenship')?.hasError('required')"> Cityzenship </mat-error>
</mat-form-field>
<mat-form-field appearance="outline" class="full-width">
<mat-label>Date of Birth</mat-label>
<input matInput formControlName="date_of_birth" [matDatepicker]="picker_birth" placeholder="Choose a date" required />
<mat-datepicker-toggle matSuffix [for]="picker_birth"></mat-datepicker-toggle>
<mat-datepicker #picker_birth></mat-datepicker>
<mat-error *ngIf="addAuthorForm.get('date_of_birth')?.hasError('required')"> Date of Birth is required </mat-error>
</mat-form-field>
<mat-form-field appearance="outline" class="full-width">
<mat-label>Date of Death</mat-label>
<input matInput formControlName="date_of_death" [matDatepicker]="picker_death" placeholder="Choose a date" />
<mat-datepicker-toggle matSuffix [for]="picker_death"></mat-datepicker-toggle>
<mat-datepicker #picker_death></mat-datepicker>
</mat-form-field>
</mat-card-content>
<mat-card-actions>
<button (click)="onCancel()" mat-button type="button">Cancel</button>
<button mat-raised-button color="primary" type="submit" (click)="onSubmit()" [disabled]="!addAuthorForm.valid">Save</button>
</mat-card-actions>
</form>
</mat-card>
Il codice è un template di componente Angular che definisce un form per aggiungere un nuovo autore. Usa componenti Angular Material per gli elementi della UI e definisce un componente di form riutilizzabile per inserire le informazioni sull’autore, sfruttando Angular Material per un’interfaccia coerente e gradevole. Il form include una validazione che garantisce la compilazione dei campi obbligatori prima dell’invio.
Nel nostro style.scss aggiungiamo:
.add-author-card {
margin-top: 20px;
}
Infine aggiorniamo add-new-author.component.ts come segue:
import { AuthorRequest } from "./../../../core/api/v1/model/authorRequest";
import { Component, EventEmitter, OnInit, Output } from "@angular/core";
import { MatCardModule } from "@angular/material/card";
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatInputModule } from "@angular/material/input";
import { MatButtonModule } from "@angular/material/button";
import { MatDatepickerModule } from "@angular/material/datepicker";
import { DateAdapter, MAT_DATE_FORMATS, MAT_NATIVE_DATE_FORMATS, MatNativeDateModule, NativeDateAdapter } from "@angular/material/core";
import { FormGroup, Validators, ReactiveFormsModule, FormBuilder } from "@angular/forms";
import { NgIf } from "@angular/common";
import { Author, LibraryAuthorsCreateRequestParams, LibraryBooksCreateRequestParams, LibraryService } from "../../../core/api/v1";
import { LibraryNotificationService } from "../../services/library-notification.service";
@Component({
selector: "app-add-new-author",
templateUrl: "./add-new-author.component.html",
styleUrl: "./add-new-author.component.scss",
imports: [MatCardModule, MatFormFieldModule, MatInputModule, MatButtonModule, MatDatepickerModule, MatNativeDateModule, ReactiveFormsModule, NgIf],
providers: [
{ provide: DateAdapter, useClass: NativeDateAdapter },
{ provide: MAT_DATE_FORMATS, useValue: MAT_NATIVE_DATE_FORMATS },
],
})
export class AddNewAuthorComponent implements OnInit {
addAuthorForm!: FormGroup;
@Output() authorAdded: EventEmitter<Author> = new EventEmitter();
@Output() authorCancelled: EventEmitter<void> = new EventEmitter();
constructor(private fb: FormBuilder, private readonly libraryService: LibraryService, private readonly libraryNotificationService: LibraryNotificationService) {}
ngOnInit() {
this.addAuthorForm = this.fb.group({
first_name: ["", Validators.required],
last_name: ["", Validators.required],
citizenship: ["", Validators.required],
date_of_birth: ["", Validators.required],
date_of_death: [""],
});
}
onSubmit() {
if (this.addAuthorForm.valid) {
const authorValue: Author = this.addAuthorForm.value;
let AuthorRequest: AuthorRequest = {
first_name: authorValue.first_name,
last_name: authorValue.last_name,
citizenship: authorValue.citizenship,
date_of_birth: this.formatDate(this.addAuthorForm.value.date_of_birth),
date_of_death: this.addAuthorForm.value.date_of_death ? this.formatDate(this.addAuthorForm.value.date_of_death) : undefined,
};
const params: LibraryAuthorsCreateRequestParams = {
authorRequest: AuthorRequest,
};
this.libraryService.libraryAuthorsCreate(params).subscribe({
next: (author) => {
console.log("Author added successfully:", author);
this.libraryNotificationService.notify({
message: "Author added successfully",
type: "success",
duration: 3000,
});
this.authorAdded.emit(author);
this.addAuthorForm.reset();
},
error: (error) => {
console.error("Error adding author:", error);
const errorMessage = error?.error || {};
let errorMessageString = "<br><br>";
for (const key in errorMessage) {
errorMessageString += `<strong>${key}</strong>: ${errorMessage[key][0]}<br><br>`;
}
// Handle error response
this.libraryNotificationService.notify({
message: "Error adding author \n" + errorMessageString,
type: "error",
duration: 3000,
});
},
});
} else {
this.addAuthorForm.markAllAsTouched();
console.log("Form is invalid");
}
}
onCancel() {
this.authorCancelled.emit();
this.addAuthorForm.reset();
}
/**
* Helper function to format a Date object into 'YYYY-MM-DD' string format.
* @param date - The date to format.
* @returns The formatted date string.
*/
private formatDate(date: Date): string {
const d = new Date(date);
let month = "" + (d.getMonth() + 1);
let day = "" + d.getDate();
const year = d.getFullYear();
if (month.length < 2) month = "0" + month;
if (day.length < 2) day = "0" + day;
return [year, month, day].join("-");
}
}
Il codice fornito definisce un componente Angular chiamato AddNewAuthorComponent, pensato per gestire la creazione di nuovi autori in un sistema di library. Questo componente usa Angular Material per gli elementi della UI e i Reactive Forms di Angular per la gestione e la validazione del form.
Caratteristiche principali:
- Inizializzazione del form:
- L’
addAuthorFormviene inizializzato nell’hook del ciclo di vitangOnInittramiteFormBuilder. Contiene i campifirst_name,last_name,citizenship,date_of_birthedate_of_death. - Vengono applicati dei validatori per garantire che i campi obbligatori siano compilati prima dell’invio.
- L’
- Event Emitter:
- Il componente definisce due proprietà
@Output:authorAddedeauthorCancelled. Emettono eventi quando un autore viene aggiunto con successo o quando il form viene annullato, permettendo ai componenti padre di reagire di conseguenza.
- Il componente definisce due proprietà
La riga di codice selezionata definisce una proprietà Angular @Output chiamata authorAdded. Questa proprietà è un’istanza di EventEmitter, una classe fornita da Angular per facilitare la comunicazione tra un componente figlio e il suo componente padre.
Spiegazione:
- Decoratore
@Output:- Il decoratore
@Outputcontrassegna la proprietàauthorAddedcome proprietà di output del componente. Ciò significa che il componente può emettere eventi tramite questa proprietà e i componenti padre possono ascoltarli usando la sintassi di event binding di Angular (ad esempio(authorAdded)="onAuthorAdded($event)").
- Il decoratore
EventEmitter:EventEmitterè una classe generica fornita da Angular. In questo caso è parametrizzata con il tipoAuthor, a indicare che gli eventi emessi da questa proprietà trasporteranno dati di tipoAuthor.
- Scopo:
- La proprietà
authorAddedserve a notificare al componente padre che un nuovo autore è stato aggiunto con successo. L’evento emesso includerà in genere come payload l’oggettoAuthorappena creato, permettendo al componente padre di aggiornare il proprio stato o di eseguire altre azioni (ad esempio aggiornare un elenco di autori).
- La proprietà
- Inizializzazione:
- La proprietà
authorAddedviene inizializzata come una nuova istanza diEventEmitter. Questo permette al componente di chiamare il metodoemit()su questa proprietà per inviare eventi al componente padre.
- La proprietà
Questa riga di codice fa parte dell’API di un componente figlio e gli permette di comunicare con il suo componente padre. Emettendo eventi tramite la proprietà authorAdded, il componente figlio può informare il padre dell’avvenuta aggiunta di un nuovo autore, facilitando un’interazione fluida tra i due componenti.
- Invio del form:
- Il metodo
onSubmitviene attivato quando il form viene inviato. Valida il form e costruisce un oggettoAuthorRequestcon i dati del form. - Viene chiamato il metodo
libraryService.libraryAuthorsCreateper inviare i dati all’API di backend. Se la richiesta ha successo, viene mostrata una notifica di successo e viene emesso l’eventoauthorAddedcon l’autore appena creato. Se la richiesta fallisce, viene mostrata una notifica di errore con messaggi di errore dettagliati.
- Il metodo
L’AddNewAuthorComponent offre un form comodo da usare con validazione, si integra con un’API di backend per l’invio dei dati e usa le notifiche per informare l’utente sull’esito dell’operazione. L’uso degli event emitter garantisce che il componente possa comunicare senza problemi con i suoi componenti padre.
Ora aggiorniamo AddNewBookComponent per gestire un nuovo autore. Aggiornamento del campo Author:
<!-- Author Field -->
<mat-form-field appearance="outline" class="full-width">
<mat-label>Author</mat-label>
<input matInput formControlName="author" placeholder="Enter author name" required [matAutocomplete]="auto" />
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
@for (author of filteredOptions | async; track author.id) {
<mat-option [value]="author"> {{ author.first_name }} {{ author.last_name }} </mat-option>
}
</mat-autocomplete>
<mat-hint align="end">
<strong>
<a mat-button (click)="toggleNewAuthor()"> @if (!newAuthor) { Add new author } @else { Select existing author } </a>
</strong>
</mat-hint>
<mat-error *ngIf="addBookForm.get('author')?.hasError('required')"> Author is required </mat-error>
</mat-form-field>
<div *ngIf="newAuthor">
<app-add-new-author (authorCancelled)="onAuthorCancelled()" (authorAdded)="onAuthorAdded($event)"></app-add-new-author>
</div>
Questo codice aggiunge un pulsante che ci permette di mostrare il componente app-add-new-author.
Ora aggiungiamo dei nuovi metodi nel file .ts:
toggleNewAuthor(): void {
// Logic to add a new author
// This could involve opening another dialog or navigating to an author creation page
console.log('Add new author clicked');
this.newAuthor = !this.newAuthor; // Toggle the new author form visibility
if (this.newAuthor) {
this.authorControl.setValue(''); // Clear the author control value
this.authorControl.disable(); // Enable the author control when adding a new author
} else {
this.authorControl.enable(); // Disable the author control when adding a new author
}
}
onAuthorCancelled() {
this.newAuthor = false; // Reset the new author form visibility
this.authorControl.enable(); // Re-enable the author control
}
onAuthorAdded(author: Author) {
console.log('Author added:', author);
this.newAuthor = false; // Reset the new author form visibility
this.addBookForm.controls['author'].setValue(author);
this.authorControl.enable(); // Re-enable the author control
}
Questo è il codice completo di add-new-book.component.ts:
// src/app/modules/library/components/add-new-book/add-new-book.component.ts
import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule, FormControl } from "@angular/forms";
import { MatDialogRef } from "@angular/material/dialog";
import { Author, BookRequest, LibraryAuthorsListRequestParams, LibraryBooksCreateRequestParams, LibraryService } from "../../../core/api/v1"; // Adjust path as needed
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatInputModule } from "@angular/material/input";
import { MatButtonModule } from "@angular/material/button";
import { MatDatepickerModule } from "@angular/material/datepicker";
import { MatAutocompleteModule } from "@angular/material/autocomplete";
import { DateAdapter, MAT_DATE_FORMATS, MAT_NATIVE_DATE_FORMATS, MatNativeDateModule, NativeDateAdapter } from "@angular/material/core";
import { CommonModule, NgIf } from "@angular/common";
import { MatDialogModule, MatDialogTitle, MatDialogContent, MatDialogActions } from "@angular/material/dialog";
import { map, Observable, startWith, switchMap } from "rxjs";
import { LibraryNotificationService } from "../../services/library-notification.service";
import { AddNewAuthorComponent } from "../add-new-author/add-new-author.component";
@Component({
selector: "app-add-new-book",
imports: [
CommonModule,
ReactiveFormsModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
MatDatepickerModule,
MatNativeDateModule,
MatDialogModule,
MatDialogTitle,
MatDialogContent,
MatDialogActions,
MatAutocompleteModule,
AddNewAuthorComponent,
NgIf,
],
providers: [
{ provide: DateAdapter, useClass: NativeDateAdapter },
{ provide: MAT_DATE_FORMATS, useValue: MAT_NATIVE_DATE_FORMATS },
],
templateUrl: "./add-new-book.component.html",
styleUrls: ["./add-new-book.component.scss"],
})
/**
* Component for adding a new book to the library.
*
* This component provides a form for entering book details, including title, author, and publication date.
* It features an autocomplete input for selecting authors, which fetches matching authors from the backend as the user types.
* Upon form submission, the component validates the input, formats the data as required by the API, and sends a request to create the new book.
* The dialog is closed upon successful creation or cancellation.
*
* @remarks
* - Uses Angular Reactive Forms for form handling and validation.
* - Integrates with the `LibraryService` to fetch authors and create books.
* - Utilizes Angular Material Dialog for modal functionality.
* - Implements an autocomplete feature for author selection.
*
* @see LibraryService
*/
export class AddNewBookComponent implements OnInit {
addBookForm!: FormGroup;
filteredOptions: Observable<Author[]> | undefined;
newAuthor = false;
authorControl = new FormControl("", Validators.required);
/**
* Initializes a new instance of the AddNewBookComponent.
*
* @param fb - The FormBuilder service used to create and manage reactive forms.
* @param dialogRef - Reference to the dialog opened for adding a new book.
* @param libraryService - Service for interacting with the library's data and operations.
*/
constructor(
private fb: FormBuilder,
public dialogRef: MatDialogRef<AddNewBookComponent>,
private libraryService: LibraryService,
private libraryNotificationService: LibraryNotificationService
) {}
/**
* Initializes the add book form and sets up the filtered options for the author autocomplete.
*
* - Creates a reactive form group with controls for title, author, and publication date.
* - Sets up an observable (`filteredOptions`) that listens to changes in the author input,
* and filters the available author options accordingly.
* - Uses `startWith` to initialize the filter and `switchMap` to handle asynchronous filtering logic.
*/
ngOnInit(): void {
this.addBookForm = this.fb.group({
title: ["", Validators.required],
author: this.authorControl,
publication_date: ["", Validators.required],
});
this.filteredOptions = this.authorControl.valueChanges.pipe(
startWith(""),
switchMap((value) => {
if (typeof value === "string") {
return this._filter(value);
}
return [[]];
})
);
}
/**
* Formats an Author object into a display string.
*
* @param author - The Author object to format.
* @returns The author's full name as a string, or an empty string if the author or first name is not provided.
*/
displayFn(author: Author): string {
return author ? author.first_name + " " + author.last_name : "";
}
/**
* Filters authors based on the provided name by querying the library service.
*
* @param name - The search string used to filter authors.
* @returns An Observable emitting an array of Author objects matching the search criteria.
*/
private _filter(name: string): Observable<Author[]> {
const params: LibraryAuthorsListRequestParams = {
search: name,
pageSize: 3,
};
return this.libraryService.libraryAuthorsList(params).pipe(map((data) => (data && Array.isArray(data.results) ? data.results : [])));
}
/**
* Handles the form submission. If the form is valid, it formats the data,
* calls the library service to create the book, and closes the dialog on success.
*/
onSubmit(): void {
console.log("Form submitted:", this.addBookForm.value);
if (this.addBookForm.valid) {
// Ensure date is formatted correctly if needed by the API (e.g., YYYY-MM-DD)
const formattedDate = this.formatDate(this.addBookForm.value.publication_date);
const bookRequest: BookRequest = {
title: this.addBookForm.value.title,
author: this.addBookForm.value.author ? this.addBookForm.value.author.id : null,
publication_date: formattedDate,
};
const bookData: LibraryBooksCreateRequestParams = {
bookRequest: bookRequest,
};
this.libraryService.libraryBooksCreate(bookData).subscribe({
next: (response) => {
console.log("Book added successfully", response);
this.libraryNotificationService.notify({
message: "Book added successfully",
type: "success",
duration: 3000,
});
this.dialogRef.close(true);
},
error: (error) => {
const errorMessage = error?.error || {};
let errorMessageString = "<br><br>";
for (const key in errorMessage) {
errorMessageString += `<strong>${key}</strong>: ${errorMessage[key][0]}<br><br>`;
}
// Handle error response
this.libraryNotificationService.notify({
message: "Error adding book \n" + errorMessageString,
type: "error",
duration: 3000,
});
},
});
} else {
this.addBookForm.markAllAsTouched();
}
}
/**
* Closes the dialog without submitting the form.
*/
onCancel(): void {
this.dialogRef.close(); // Close dialog without passing any data
}
/**
* Helper function to format a Date object into 'YYYY-MM-DD' string format.
* @param date - The date to format.
* @returns The formatted date string.
*/
private formatDate(date: Date): string {
const d = new Date(date);
let month = "" + (d.getMonth() + 1);
let day = "" + d.getDate();
const year = d.getFullYear();
if (month.length < 2) month = "0" + month;
if (day.length < 2) day = "0" + day;
return [year, month, day].join("-");
}
toggleNewAuthor(): void {
// Logic to add a new author
// This could involve opening another dialog or navigating to an author creation page
console.log("Add new author clicked");
this.newAuthor = !this.newAuthor; // Toggle the new author form visibility
if (this.newAuthor) {
this.authorControl.setValue(""); // Clear the author control value
this.authorControl.disable(); // Enable the author control when adding a new author
} else {
this.authorControl.enable(); // Disable the author control when adding a new author
}
}
onAuthorCancelled() {
this.newAuthor = false; // Reset the new author form visibility
this.authorControl.enable(); // Re-enable the author control
}
onAuthorAdded(author: Author) {
console.log("Author added:", author);
this.newAuthor = false; // Reset the new author form visibility
this.addBookForm.controls["author"].setValue(author);
this.authorControl.enable(); // Re-enable the author control
}
}
Finalmente possiamo aggiungere il nostro libro “The Hunger Games”:


Lascia un commento