Book Image

Angular Design Patterns

By : Mathieu Nayrolles
Book Image

Angular Design Patterns

By: Mathieu Nayrolles

Overview of this book

This book is an insightful journey through the most valuable design patterns, and it will provide clear guidance on how to use them effectively in Angular. You will explore some of the best ways to work with Angular and how to use it to meet the stability and performance required in today's web development world. You’ll get to know some Angular best practices to improve your productivity and the code base of your application. We will take you on a journey through Angular designs for the real world, using a combination of case studies, design patterns to follow, and anti-patterns to avoid. By the end of the book, you will understand the various features of Angular, and will be able to apply well-known, industry-proven design patterns in your work.
Table of Contents (9 chapters)

Factory method

Let's assume that we have a User class with two private variables: lastName:string and firstName:string. In addition, this simple class proposes the hello method that prints "Hi I am", this.firstName, this.lastName:

class User{
constructor(private lastName:string, private firstName:string){
}
hello(){
console.log("Hi I am", this.firstName, this.lastName);
}
}

Now, consider that we receive users through a JSON API. It'll more than likely look something like this:

[{"lastName":"Nayrolles","firstName":"Mathieu"}...].  

With the following snippet, we can create a User:

let userFromJSONAPI: User = JSON.parse('[{"lastName":"Nayrolles","firstName":"Mathieu"}]')[0];

Until now, the TypeScript compiler doesn't complain, and...