Book Image

Angular Design Patterns and Best Practices

By : Alvaro Camillo Neto
2 (1)
Book Image

Angular Design Patterns and Best Practices

2 (1)
By: Alvaro Camillo Neto

Overview of this book

Single page applications (SPAs) have become the standard for most web experiences. Angular, with its batteries-included approach, has emerged as a powerful framework for simplifying the development of these interfaces by offering a comprehensive toolbox. This book guides you through the Angular ecosystem, uncovering invaluable design patterns and harnessing its essential features. The book begins by laying a strong foundation, helping you understand when and why Angular should be your web development framework of choice. The next set of chapters will help you gain expertise in component design and architecting efficient, flexible, and high-performing communication patterns between components. You’ll then delve into Angular's advanced features to create forms in a productive and secure way with robust data model typing. You'll also learn how to enhance productivity using interceptors to reuse code for common functionalities, such as token management, across various apps. The book also covers micro frontend architecture in depth to effectively apply this architectural approach and concludes by helping you master the art of crafting tests and handling errors effortlessly. By the end of this book, you'll have unlocked the full potential of the Angular framework.
Table of Contents (19 chapters)
1
Part 1: Reinforcing the Foundations
7
Part 2: Leveraging Angular’s Capabilities
12
Part 3: Architecture and Deployment

Changing the request route

In our project so far, we have two services that make requests to the backend. If we analyze them, we see that they both point directly to the backend URL. This is not a good practice since, as the project scales and grows in complexity, errors can occur by pointing to the wrong URL. In addition to the need to change the host, we will need to change numerous files.

There are a few ways to handle this problem, but a very useful tool for this is the Angular interceptor. Let’s see it in practice starting with the Angular CLI, where we are going to create the new interceptor:

ng g interceptor shared/host

With the generated file, let’s create the intercept function:

@Injectable()
export class HostInterceptor implements HttpInterceptor {
  intercept(
    request: HttpRequest<unknown>,
    next: HttpHandler
  ): Observable<HttpEvent<unknown>> {
   ...