28,99 €
Manage state in Angular to write high performing web apps by combining the power of Flux, RxJS, and NgRx
Key Features- Learn what makes an excellent Angular application architecture- Use Redux to write performant, consistent Angular applications- Incorporate Reactive Programming principles and RxJS to make it easier to develop, test, and debug your Angular applicationsBook Description
Managing the state of large-scale web applications is a highly challenging task with the need to align different components, backends, and web workers harmoniously. When it comes to Angular, you can use NgRx, which combines the simplicity of Redux with the reactive programming power of RxJS to build your application architecture, making your code elegant and easy to reason about, debug, and test.
In this book, we start by looking at the different ways of architecting Angular applications and some of the patterns that are involved in it. This will be followed by a discussion on one-way data flow, the Flux pattern, and the origin of Redux.
The book introduces you to declarative programming or, more precisely, functional programming and talks about its advantages. We then move on to the reactive programming paradigm. Reactive programming is a concept heavily used in Angular and is at the core of NgRx. Later, we look at RxJS, as a library and master it. We thoroughly describe how Redux works and how to implement it from scratch. The two last chapters of the book cover everything NgRx has to offer in terms of core functionality and supporting libraries, including how to build a micro implementation of NgRx.
This book will empower you to not only use Redux and NgRx to the fullest, but also feel confident in building your own version, should you need it.
What you will learnUnderstand the one-way data flow and Flux patternWork with functional programming and asynchronous data streamsFigure out how RxJS can help us address the flaws in promisesSet up different versions of cascading callsExplore advanced operatorsGet familiar with the Redux pattern and its principlesTest and debug different features of your applicationBuild your own lightweight app using Flux, Redux, and NgRxWho this book is for
If you have been developing Angular applications and want to dive deeper into the Angular architecture with Redux, RxJS, and NgRx to write robust web apps, then this book is for you.
Christoffer Noring, a software developer with over 10 years' experience, has successfully delivered software for industries ranging from telecom to aviation. He has worked on everything from databases to frontend. Frequently speaking on TDD, React, NativeScript, RxJS, and Angular, he writes books and blogs and holds the title of Google Developer Expert in Web Technologies and Angular. Currently working for McKinsey as a full stack developer, he's the author and maintainer of RxJS Ultimate, and he has coauthored Learning Angular - Second Edition, a Packt title.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 395
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Ashwin NairAcquisition Editor: Reshma RamanContent Development Editor: Nikhil BorkarTechnical Editor: Subhalaxmi NadarCopy Editor: Safis EditingProject Coordinator: Ulhas KambaliProofreader: Safis EditingIndexer: Rekha NairGraphics: Tania DuttaProduction Coordinator: Shraddha Falebhai
First published: March 2018
Production reference: 1230318
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78712-240-6
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Programming is all about solving problems, and effective problem solving is all about breaking down big problems into little ones; this makes the problem digestible. You can eat an elephant if you do it one bite at a time.
One of the more recent advancements in breaking down problems into smaller pieces is Redux-style state management, which for Angular means NgRx. Learning NgRx and knowing how to use it effectively in your applications will provide a high return on investment as you and your team will be able to keep your code clean and keep your velocity from degrading over time. This book will teach you how to use NgRx and use it effectively.
Joe Eames
Software craftsman
Christoffer Noring, a software developer with over 10 years' experience, has successfully delivered software for industries ranging from telecom to aviation. He has worked on everything from databases to frontend. Frequently speaking on TDD, React, NativeScript, RxJS, and Angular, he writes books and blogs and holds the title of Google Developer Expert in Web Technologies and Angular.
Currently working for McKinsey as a full stack developer, he's the author and maintainer of RxJS Ultimate, and he has coauthored Learning Angular - Second Edition, a Packt title.
Mashhood Rastgar is the founder and technical lead at Recurship, which is a JavaScript consultancy based in Karachi, Pakistan. He is also part of the Google Developer Experts for Web and Angular. Mashhood works startups working in EU and USA, to help them crawl through the technical maze and quickly build amazing products focused around the problems they are trying to solve. He specializes in using the latest technologies available to identify the best solutions. He is also a frequent international and local speaker at different web conferences.
Vinci Rufus is a Google Developer Expert and Senior Director with SapientRazorfish. He consults clients and teams on frontend architecture, mobile strategy, and user experience, primarily in the areas of content and commerce. His areas of interest involve progressive web apps, Angular, React, and web components. He is an author of AngularJS Web Application Development Blueprints.
Sachin Ohri is a technology architect with a keen interest in web-based technologies. He has been writing web applications for more than a decade, with technologies such as .NET, JavaScript, Durandal, Angular, and TypeScript. He works on providing technical solutions, including architectural design, technical support, and development expertise, to Fortune 500 companies. He holds various Microsoft certifications, such as Microsoft Azure Architect, Microsoft ASP.NET MVC web application, and Microsoft Programming with C#.
Andrew Leith Macrae first cut his programming teeth on an Apple IIe, poking bytes into the RAM. Over the years, he has developed interactive applications with Hypercard, Director, Flash, and more recently, Adobe AIR for mobile. He has also worked with HTML since there was HTML to work with and is currently working as a senior frontend developer at The Learning Channel, using Angular 4 with TypeScript.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Architecting Angular Applications with Redux, RxJS, and NgRx
Packt Upsell
Why subscribe?
PacktPub.com
Foreword
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Quick Look Back at Data Services for Simple Apps
Model-View-Controller – the pattern we all know
Cohesion and coupling – establishing a common language
Explaining the components of MVC
The model
The view
The controller
Interactions – the behavior between the components
MVC summary
An MVC flow in Angular
The model
The component – a controller and a building block
First responder to a route
Used as a building block
Components from an architectural standpoint
NgModule – our new facade (and some other bits)
Using ES2015 modules
Consuming a module
An Angular example
Multiple exports
The default import/export
Renaming imports
The service
Service without dependencies
Service with dependencies
Dependency Injection
Dependency Injection in Angular using providers
Overriding an existing construct
Overriding at runtime
Overriding constants
Resolving your dependencies with @Injectable
Fetching and persisting data with HTTP – introducing services with Observables
Fetching data with the HTTP service
Summary
1.21 Gigawatt – Flux Pattern Explained
Core concepts overview
A uniform data flow
Action – capture the intent
Dispatcher – the spider in the web
Listening to the dispatcher
The store – managing state, data retrieval, and callbacks
The view
Demoing a uniform data flow
Creating a selection view
Adding the dispatcher
Adding the store
Adding a selected view
Running the demo
Adding more actions to our flow
Cleaning up the view
Cleaning up the store
Adding EventEmitter
Adding to and cleaning up the register method
Further improvements
Adding immutability
Summarizing
Adding AJAX calls
An even bigger solution
Summary
Asynchronous Programming
The callback pattern
The callback pattern on the web
The callback pattern in Node.js
Problems with structuring async code – callback hell
Promises
Thenables
Handling rejected promises
Chaining – dealing with several promises
Asynchronous libraries
Async library
async.map()
async.parallel()
async.series()
Async/await
Summary
Functional Reactive Programming
Functional programming versus imperative programming
Imperative programming versus declarative programming
First-class higher-order functions
Pure functions
Recursion
No more loops
Reoccurring pattern
Summarise
Count
Width
Asynchronous data streams
Comparing lists to async streams – preparing for RxJS
Combining the functional programming paradigm with streams
Projection
Filtering
Combining mindsets
Summary
RxJS Basics
Observer pattern
RxJS core concepts
Observable and Observer
Producer
Observable error and completion
Operator
Creating Observables
Creation operators
of()
interval()
from()
fromEvent()
bindCallback()
Cleanup
Subscriptions
Creating a core implementation of RxJS
Implementing create()
Handling subscriptions
Adding operators
Revisiting the basics, adding errors, and complete
Summary
Manipulating Streams and Their Values
Starting out
Understanding operators
Stream in a stream
AJAX
fetch()
ajax() operator
Cascading calls
A deeper look
Creation operators
of() operator
from() operator
range() operator
fromEvent() operator
Combination
merge() operator
combineLatest()
zip()
concat()
Mathematical
max
min
sum
Time
interval() operator
timer() operator
delay() operator
sampleTime() operator
debounceTime() operator
Grouping
buffer() operator
bufferTime() operator
Thinking in streams
Summary
RxJS Advanced
Hot, cold, and warm Observables
Making a stream hot
Warm streams
Subjects
Using Subject for cascading lists
BehaviorSubject
ReplaySubject
AsyncSubject
Error handling
Catch and continue
Ignoring the error 
Retry
Advanced Retry
Marble testing
Set up
Writing your first marble test
Fleshing out with more tests
Pipeable operators
Creating reusable operators with let()
Shifting to pipeable operators
Summary
Redux
Principles
Single source of truth
Read-only states
Changing states with pure functions
Core concepts
Immutability patterns
Changing a list
Changing an object
Using reducers
Merging all reducers together
Data flow
Creating the action
Creating a controller class – create-view.js
Creating a store implementation
Testing out our store
Cleaning up the implementation
Creating our second controller class – list-view.js
Adding subscription capability to our store
Creating a program
Setting up our environment
Creating the missing files and running our program
Dealing with asynchronous calls
Creating a demo with Redux and asynchronous
Best practices
Summary
NgRx – Reduxing that Angular App
NgRx overview
A word on state management
@ngrx/store – state management
A more complex example – a list
Best practices
A cleanup example
Create a dedicated directory and feature module
Add reducer and constants
Moving the component to our jedi directory
Registering our reducer with the store
Leveraging types and feature modules
Going from forRoot() to forFeature()
Setting up forFeature() from string to selection function
Introducing NgRx types for setting up the state
Giving forFeature() a type
Several states in the same feature module
Adding the counter-list reducer
Adding the component
Adding the constants
Adding the action methods
Adding the model
Register our reducers
Component architecture
@ngrx/store-devtools – debugging
@ngrx/effects – working with side effects
Installing and setting it up 
Creating our first effect – a realistic scenario
Creating our constants
Action creators
Reducer with a new type of default state
The effect – listening to a specific dispatched action
Adding a component – introducing selectors
Extending our example with the create effect
Updating the constants file
Updating the reducer
Additional actions 
Adding another effect
Supporting the effect in our component
Running a demo of the app
Summary
NgRx – In Depth
@ngrx/entity
Setting it up
Selecting our data
Adding the full CRUD
Creating users
Updating users
Deleting users
@ngrx/router-store
Installation and set up
Investigating the router state
Custom serialization
Navigating through dispatch
Understanding NgRx – building our own micro implementation
Adding a store
Merging the states in a better way
Implementing a reducer and integrating it with the store
Dealing with slices of state
Handling side effects
@ngrx/schematics
Setting it up
Generating constructs
Generating actions
Generating a container
Generating an effect
Generating an entity
Generating a feature
Generating a reducer
Generating a store
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
NgRx is an implementation of the popular pattern, Redux, that's meant for use with Angular. It is entirely possible to create an Angular application without NgRx. You might even be very successful in doing so. There are situations, though, where Redux can really help; you can get that help by using NgRx.
So, what is Redux and when do we need it? Redux is about adding predictability to your app. Predictability is about knowing who did what to the state in your application.
Single source of truth is a concept that Redux lives up to as it promotes adding all your data to one store. At any given moment, you will be able to tell what state your application is in. This is great if you want to save the state and come back to it (also called rehydration) like you would in a game where you create a save point and later resume your game from that save point.
It's not only about having a single source of truth; it's also about knowing who is allowed to change the content, or the state, of the store. A challenge you often face is that as an application grows, you need to add a lot of views and controllers, you gradually lose the overview of what code affects what state in the application. Redux helps you with this by ensuring that a view can't change the state directly but will have to dispatch actions that represent the intent of how you want the state to change.
Another thing that might happen is that a lot of user interaction kicks off a lot of changes to the state. Some of those actions should lead to immediate changes and some lead to asynchronous actions that will eventually change the state of the application. The important thing at this point is that we ensure that all those changes happen in the right order. Redux helps us with that by queuing up all the actions and ensures that our app changes its state in a predictable way.
A very important aspect of Redux is that when it changes the state, it does not mutate it. It replaces the state with a copy of the old state, but with the latest action applied to it. If we take our game analogy again, imagine that you have a game and you want to add a potion to your backpack. When you do that in Redux, we replace the main character; we replace it with a main character that has a potion in its backpack. The fact that we do things this way makes it easy for us to remember each previous state and return to an earlier state if we need to, which is known as time-travel-debugging. To enable us to replace the previous state with a new state, we are using something called pure functions. Pure functions ensure that we only create a copy of the data instead of mutating it.
There are a lot of benefits to knowing what state your app contains at a given point. However, not all the state in your app will need Redux. It comes down to preference. Some prefer to put all the state in the store, some prefer to put some state in the store, and some other state is fine if it only lives as local state in a specific component. Think of it this way, if you were to restore your app, what state would be okay to lose; the answer may be a drop-down selection made or something else, if anything. Having everything in the store will ensure that you don't, by mistake, make extra Ajax calls if the store already holds the data, so it is a way of helping you with caching as well.
This book is intended for Angular developers who have written an app or two and are looking for a more structured way to handle data management. This means you ideally have a decent grasp of JavaScript, HTML, and CSS and know how to scaffold an Angular application using angular-cli, and you also know how to make AJAX requests using the HttpClient service in Angular.
Chapter 1, Quick Look Back at Data Services for Simple Apps, covers how to work with services and how Angular dependency injection helps out. It also brings up the MVC pattern and discusses cohesion and coupling.
Chapter 2, 1.21 Gigawatt – Flux Pattern Explained, teaches what the Flux pattern is and what concepts it consists of. It shows how to implement the Flux pattern using stores, a dispatcher, and several views.
Chapter 3, Asynchronous Programming, looks at what asynchronous means and talks about callbacks, promises, async/await, and how the async library can help us create order in our asynchronous code.
Chapter 4, Functional Reactive Programming, compares declarative and imperative programming and looks at a subset of declarative programming, functional programming. We drill down into certain properties of functional programming, such as higher-order functions, immutability, and recursion. Furthermore, we look at how to make code reactive and what reactive means.
Chapter 5, RxJS Basics, introduces the RxJS library. Furthermore, it brings up concepts such as Observable, Producer, and Observer. It further discusses how the Observable is the asynchronous concept that we need to unify all our asynchronous concepts into one. We also touch on operators and what they are. Lastly, we attempt to build our own micro implementation of RxJS to further understand what's going on under the hood.
Chapter 6, Manipulating Stream and Their Values, focuses a lot on educating the reader on operators, the thing that gives RxJS its power. The reader should leave this chapter with a lot more knowledge about how to manipulate data as well as Observables.
Chapter 7, RxJS Advanced, goes deeper and tries to explain more advanced concepts in RxJS, such as hot and cold Observables, subjects, error handling, and how to test your RxJS code with Marble testing.
Chapter 8, Redux, demonstrates the Redux pattern and explains how it came from the Flux pattern and improved upon some of its paradigms and concepts. The reader will learn how it works in practice by learning to build their own Redux and also using the same, involving a couple of views.
Chapter 9, NgRx – Reduxing that Angular App, explores what NgRx is and what it consists of. It also shows the reader how to put it in to use by adding it to an Angular application. Concepts such as store are explained and demoed, and the reader will learn how to debug and handle side effects with the Effects library.
Chapter 10, NgRx – In Depth, covers the Entity library, which allows you to write way less code by reducing a lot of boilerplate. It also shows how you can put a router's state in the store. Furthermore, we look at how to test NgRx, how to build it yourself, and lastly, we cover Schematics, which will help us further by allowing us to scaffold the most common constructs we need to work with in NgRx.
This book is about building Angular applications using NGRX. To get the most out of the book you need a basic understanding of the Angular framework and should be able to scaffold an Angular application using the Angular-CLI or be able to set up an Angular project through Webpack, if that is your preferred way. It's good to have a decent understanding of JavaScript and TypeScript. Most of all a curious mind is really all you need. It's a good idea to have NodeJs installed on your machine.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Architecting-Angular-Applications-with-Redux-RxJs-and-NgRx. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "We need to install webpack by typing the following in our terminal."
A block of code is set as follows:
interface IPrinter { print(IPrintable printable);}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
interface IPrintable {
String getContent();
}
interface IPrinter { print(IPrintable printable);}
Any command-line input or output is written as follows:
npm install webpack webpack-cli --save-dev
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Let's add an item to our store by adding a value to our input element and pressing the Save button."
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
Welcome to the first chapter of this book. You have hopefully picked up this book because you have experienced issues setting up the architecture of your Angular application. Your application has grown and in that process you slowly feel your are losing track of what your application knows at a given point, what we call the state of the application. There might be other issues, such as parts of your application not being in agreement with what they know. An update that happened in one part may not have been applied to some other part and you scratch your head, thinking should it be this hard and is there a better answer?
It's entirely possible you are just picking up this book as you have heard about NgRx as the way to structure your application and you are curious and want to know more.
Regardless of which motivation drives you to read this book, this book is about learning to structure your application and learning how to set up and communicate your application's state, and its changes, in a way that all parts of your application are in agreement on what is happening. The underlying architectural pattern for NgRx is Redux, which constrains data to live in only one place and ensures data is flowing in only one direction. We will have a chance to cover Redux in more depth in a dedicated chapter in this book.
To get to a point where we have learned to master NgRx, we first need to pick up some paradigms and patterns along the way. We need to build a good foundation of knowledge. A good foundation consists of learning concepts such as Functional Reactive Programming (FRP), the architectural pattern Flux, and a new and exciting way of thinking about async concepts, Observables.
So why are these relevant for our learning journey of mastering NgRx? The Flux pattern has a lot in common with Redux and it is its shortcomings that led to Redux being created. NgRx itself is implemented using RxJS, which promotes a functional reactive style of programming. So you see, the foundations we are about to explore all help us grasp the theory and motivations behind NgRx.
In this chapter, we lay the foundations for the book by discussing the well-known Model-View-Controller (MVC) pattern. To verify we understand the MVC pattern, we use the Angular framework to make things easier. As interesting as it is to talk about architecture, if you don't see it applied to something real, it might be hard to grasp.
We continue diving into an application workflow in Angular and its Dependency Injection machinery. Before concluding the chapter, we will also have a look at how to fetch data through an API because, after all, that is where the data comes from and should flow to.
In this chapter, we will:
Describe the building blocks of the MVC pattern
Describe MVC in Angular and the core constructs that help support it
Review the HTTP service and how to deal with Ajax
Regardless of whether you have been a programmer for a year or 20 years, you have almost certainly encountered the MVC pattern in some way, shape, or form. The pattern itself, MVC, consists of three interconnected parts: model, view, and controller. More important than knowing all its parts is knowing what problem it solves. It solves the problem of separation of concerns by decoupling view logic, data logic, and business logic. The MVC pattern has given rise to, among others:
Model-View-Adapter
(
MVA
)
Model-View-Presenter
(
MVP
)
Model-View-ViewModel
(
MVVM
)
Back to the MVC pattern. Using said pattern means we get high cohesion and low coupling; this is due to code being split into different layers with different responsibilities. View logic belongs in views, controller logic in controllers, and model logic in models.
This is the crucial part of the application. This does not rely on any specific user interface but more defines the domain in which you operate. Rules, logic, and data live here.
This can be anything from a native app view to a bar chart, or even a web page. The point is that it ultimately displays data from the model. There can be different views displaying the same thing, but depending on for whom they are designed, they might look different. An admin might see a totally different view than a user for the same information.
This is really the spider in the web. It is able to take input from the view or from the data and turn it into commands.
All these three mentioned components act in different ways when talking to each other. A model stores data it is being given from the controller based on commands. A view changes its appearance based on changes happening in the model. A controller can send a command to the model based on a user interaction. One such example is a user deciding to browse between page-based records. A new set of data will need to be retrieved based on the new visual position.
These two basic flows are what mostly happens in an application-based on MVC:
User interaction: Controller sends command to Model => Model changes => View is updated
View asks for data: Controller sends command to Model => Model is created/changed => View is updated
A lot can be said about MVC and its many variants, but let's be content with what we have for now by summarizing the properties of the pattern that we identified:
Low coupling
High cohesion, separating presentation concerns from the model
Simultaneous development is possible; due to the existence of many layers, people can work in parallel on a task
Ease of change; because of how things are separated, adding future concepts or making alterations becomes easier
Let's look at the following problems and how we solve them in Angular:
Creating and rendering model data to the screen
Learning how the MVC pattern maps to the Angular framework
Learning how we can structure an Angular application in different building blocks
Fetching data/persisting data
The model in Angular is a plain class, as we are using TypeScript. It can look like the following code:
// mvc/MvcExample/src/app/product.model.tsexport class Product { constructor( private id: number, private title: string, private description: string, private created: Date ) {} method() {} anotherMethod() {}}
It is a plain TypeScript file, or rather an ES2015 module, not to be confused with an Angular module. We will discuss in the next main section what an Angular module is, in terms of setup and how it is consumed. For now, remember the model is a simple thing.
In the context of MVC, the component is the V and C, the view and the controller. The component allows you to define either a separate template file or an inline template. The template is the view part.
The controller in this context is a component class file that handles user interactions and also fetches the necessary data for the template to display.
Components have come to be a central concept for a lot of frameworks that are popular today, such as React, Vue.js, and Polymer. A component can take inputs, which are either data or methods. It consists of a piece of code and an HTML template, which render interesting data, living on the component. A component in Angular consists of three major parts:
A decorator function
A class
A template
A component consists of a controller class and a template. It can play two different roles in an Angular application: either it can be the responder to the route or it can serve as a building block. In the first case, Angular will instantiate it when a new route happens and respond with that component. In the latter case, the component is created directly by existing as a child component within another component.
We will explain next what we meant by the previous paragraph.
As mentioned, a component can be used as a responder to a route. So let's say the application routes to the /products route as a result of a user interaction, or programmatically. Angular's way of dealing with this is to associate the /products route with a component. With the help of a component's class and HTML markup, we are able to produce a piece of HTML containing our markup and data rendered together. Pointing out a component as a responder to a route, is done when defining the so-called route map, like so:
// example of what routing might look likeexport
const
appRoutes
:
Routes
[
{
path:
''
,
component:
HomeComponent
},
{ path:
'payments'
,
component:
ProductsComponent
,
data:
{
title:
'Products'
} }]
Essentially, a route is defined as an object with path properties, pointing out our route, and a component property pointing to the responding component. We can attach other properties to the route, such as data, to give the responding components some initial data to render.
Using a component as a building block means it will be part of another component's template. Essentially, it will be seen as that component's child. This line of thinking is quite natural and means that we can think of our application as a hierarchical tree of components. A component in Angular consists of a controller class and a template as we have mentioned previously. A typical component looks like so:
// an example component@Component({ selector: 'example-component'})export class ExampleComponent {}
The @Component decorator function adds metadata to the class. This instructs Angular on how to create the component so that Angular can place the component in the DOM. This enables you to use it as a responder to a route or as your own custom element. The property selector is what decides what your component should be called, if used as a custom element. Example usage looks like the following:
// an example container component@Component({ selector: ` {{ title }}
<example-component>
`})export class ContainerComponent { title ="container component";}
The fact that components can be used this way makes it easy to think about an app as consisting of a hierarchical tree of components. A Todo application could therefore look like the following:
AppComponent TodoList TodoItem TodoItem TodoItem ...