What's new in Learning Angular - 4th edition
Aristeidis Bampakos
Angular Google Developer Expert | Web Developer (Angular) | Award-winning author | Speaker
Learning Angular is a book destined for beginners to the Angular framework. It teaches you how to start web development using Angular in a progressive approach. It is a step-by-step guide that walks you through scaffolding an Angular application from scratch up to testing and deploying it to production.
The new 4th edition of the book is fully updated to Angular 15 and comes packed with all the latest features that will help you build modern web applications in no time. Some of these features are:
Let's see each one in more detail.
Standalone APIs
Angular Standalone APIs provide a modern and ergonomic approach to developing Angular applications. The absence of NgModules makes it easier to grasp and understand various Angular concepts, especially for newcomers to the Angular framework. The main idea behind standalone APIs is that components, directives, and pipes do not need a compilation context from an Angular module because they import any Angular artifacts they need. A standalone artifact is indicated by the usage of the standalone property as shown in the following component example:
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
? selector: 'app-product',
? standalone: true,
? imports: [CommonModule],
? templateUrl: './product.component.html',
? styleUrls: ['./product.component.css']
})
export class ProductComponent {}
In the preceding snippet, the component uses the imports array to import directives such as NgIf and NgFor from CommonModule.
Typed Forms
The underlying typing system of reactive forms has undergone a major overhaul in Angular 15. Angular forms can now infer the type of each form control, greatly enhancing the development experience and avoiding any potential bugs in the code. Additionally, we can manually define the type of each form control?using TypeScript generics.
productForm = new FormGroup({
? name: new FormControl('', { nonNullable: true }),
? price: new FormControl<number | undefined>(undefined, { nonNullable: true })
});
In the preceding snippet, Angular can automatically deduce that the name control is of string type because it is initialized to an empty string by default. It also knows that price can be a number or undefined because we define it manually.
Functional router APIs
The new router API allows us to embrace a simpler way of creating Angular guards and resolvers using pure functions. Functional router APIs along with the new inject method provide a modern and easy-to-understand way of interacting with the router.
领英推荐
import { inject } from '@angular/core';
import { CanActivateFn, CanLoadFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuard: CanActivateFn | CanLoadFn = () => {
? const authService = inject(AuthService);
? const router = inject(Router);
? if (authService.isLoggedIn) { return true; }
? return router.parseUrl('/');
};
The new router APIs shine in cases where we had to create a whole TypeScript class to implement a one-line guard. We can now embed the guard logic inline the route configuration:
{?
path: 'cart',
? component: CartComponent,
? canActivate: [authGuard],
? canDeactivate: [() => confirm('You have pending items in your cart. Do you want to continue?')]
}
Error handling and debugging
Application errors are an integral part of the lifetime of a web application. They can occur either during runtime or while developing the application. Runtime errors may happen due to an HTTP request that failed or an incomplete HTML form. Development errors usually occur when we do not properly use a programming language or framework according to its semantics. In both cases, we need a mechanism for debugging the application to investigate and fix the error.
Application errors at runtime in Angular can be handled in different places according to the experience?we want to provide. We can create a global error handler that catches all errors that occur in our application:
export class AppErrorHandler implements ErrorHandler {
? handleError(error: any): void {
? ? const err = error.rejection || error;
? ? if (err instanceof HttpErrorResponse) {
? ? ? switch(err.status) {
? ? ? ? case 0:
? ? ? ? ? console.error('Client error:', error.error);
? ? ? ? ? break;
? ? ? ? case HttpStatusCode.BadRequest:
? ? ? ? ? console.error('Request error:', error.error);
? ? ? ? ? break;
? ? ? ? default:
? ? ? ? ? console.error('Unknown error:', error.error);
? ? ? }
? ? } else {
? ? ? console.error('Application error:', err)
? ? }
? }
}
Alternatively, we can provide a different error handling mechanism only for HTTP errors using an HTTP interceptor:
export class AuthInterceptor implements HttpInterceptor {
?
? constructor(private authService: AuthService) {}
? intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
? ? const authReq = request.clone({
? ? ? setHeaders: { Authorization: 'myAuthToken' }
? ? });
? ? return next.handle(authReq).pipe(
? ? ? catchError((error: HttpErrorResponse) => {
? ? ? ? if (error.status === HttpStatusCode.Unauthorized) {
? ? ? ? ? this.authService.logout();
? ? ? ? ? return EMPTY;
? ? ? ? } else {
? ? ? ? ? return throwError(() => error);
? ? ? ? }
? ? ? })
? ? );
? }
}
Sometimes, errors in an Angular application are difficult to spot and fix. We must debug the application to find and fix them. We can debug an Angular application using standard debugging techniques for web applications, or Angular DevTools provided out of the box.
Angular DevTools is a browser extension created and maintained by the Angular team that allows us to debug and profile Angular applications. Below you can see a simple example of how we can use Angular DevTools to inspect a component and preview its properties:
Learning Angular - 4th edition contains all the above features and much more! Get your copy today from Amazon at https://www.amazon.com/dp/1803240601 and start building modern and blazing-fast Angular applications!
Mean Stack Developer Senior on Foxconn CTBG Juarez
3 个月I won this book on angular space thanks