39,59 €
A hands-on guide with a minimalist and flexible approach that enables quick learning and rapid delivery of cloud-ready enterprise applications with Angular 6
Angular 6 for Enterprise-Ready Web Applications follows a hands-on and minimalist approach demonstrating how to design and architect high quality apps.
The first part of the book is about mastering the Angular platform using foundational technologies. You will use the Kanban method to focus on value delivery, communicate design ideas with mock-up tools and build great looking apps with Angular Material. You will become comfortable using CLI tools, understand reactive programming with RxJS, and deploy to the cloud using Docker.
The second part of the book will introduce you to the router-first architecture, a seven-step approach to designing and developing mid-to-large line-of-business applications, along with popular recipes. You will learn how to design a solid authentication and authorization experience; explore unit testing, early integration with backend APIs using Swagger and continuous integration using CircleCI. In the concluding chapters, you will provision a highly available cloud infrastructure on AWS and then use Google Analytics to capture user behavior.
By the end of this book, you will be familiar with the scope of web development using Angular, Swagger, and Docker, learning patterns and practices to be successful as an individual developer on the web or as a team in the Enterprise.
This book is for developers who want to confidently deliver high-quality and production-grade Angular apps from design to deployment. We assume that you have prior experience in writing a RESTful API with the tech stack of your choice; if you don't, you can still gain a lot of benefit from this book, which focuses on the entire scope of frontend development, from design to deployment!
Doguhan Uluca is a software development expert for Excella Consulting in Washington, DC. He is the founder and director of the polyglot Tech Talk DC meetup and the creator of the DC Full Stack Web Summit conference. Doguhan has been published on DevPro and ACM. He is a speaker at international conferences, such as Ng-Conf, CodeStock, deliver:Agile and Agile XP. He is a full-stack JavaScript, Agile, and cloud engineering practitioner. Doguhan is an active contributor to the open source community, with libraries and tools published for JavaScript, Angular, Node, and MongoDB.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 446
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:Amarabha BanerjeeAcquisition Editor:Nigel FernandesContent Development Editor:Francis CarneiroTechnical Editor:Sachin SunilkumarCopy Editor:Shaila KusanaleProject Coordinator:Devanshi DoshiProofreader: Safis EditingIndexer:Tejal Daruwale SoniGraphics:Jason MonteiroProduction Coordinator:Shantanu Zagade
First published: May 2018
Production reference: 1250518
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78646-290-9
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.
Doguhan Uluca is a software development expert for Excella Consulting in Washington, DC. He is the founder and director of the polyglot Tech Talk DC meetup and the creator of the DC Full Stack Web Summit conference. Doguhan has been published on DevPro and ACM. He is a speaker at international conferences, such as Ng-Conf, CodeStock, deliver:Agile and Agile XP. He is a full-stack JavaScript, Agile, and cloud engineering practitioner. Doguhan is an active contributor to the open source community, with libraries and tools published for JavaScript, Angular, Node, and MongoDB.
Wyn B. Van Devanter is currently a managing consultant and senior developer with Excella, an Agile tech firm. He has experience in various industries and government with architecture, design, and implementation of software, largely with web-based applications. He also works heavily with DevOps, cloud, and container-based architectures and strives to be a good software craftsman using XP practices. He enjoys being involved in the community and regularly speaks and conducts workshops at events around the region. Wyn likes playing music, skiing, and conversations of intrigue.
Brendon Caulkins is a DC-based full stack developer at Excella. His focus is Java, but he still harbors a secret love for PHP. He holds a computer engineering degree from Purdue University (Boiler Up!) and refuses to give up playing with Legos. He has nearly a decade of hardware environmental testing and software product testing experience, and is really, really good at breaking things. He is also an award-winning painter of tiny toy soldiers and goes by the name Plarzoid on the interwebs.
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
Angular 6 for Enterprise-Ready Web Applications
Packt Upsell
Why subscribe?
PacktPub.com
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
Setting Up Your Development Environment
CLI package managers
Install Chocolatey for Windows
Installing Homebrew for macOS
Git and GitHub Desktop
Why use GitHub?
Why use GitHub Desktop?
Installing Git and GitHub Desktop
Node.js
Existing Node.js Installation
Installing Node.js
Visual Studio Code
Installing Visual Studio Code
Automation for Windows and macOS
Summary
Further reading
Create a Local Weather Web Application
Introduction to Angular
Angular's philosophy
What's new in Angular 6?
Angular in Full-Stack Architecture
Wireframe design
High level architecture
Folder structure
Set up your development directory
Generate your Angular application
Installing Angular CLI
Initializing Angular app
Publishing Git Repository using GitHub Desktop
Inspecting and updating package.json
Commiting code using VS Code
Running your Angular app
Optimizing VS Code for Angular
IDE settings
IDE extensions
Coding style
Planning a feature road map using Waffle
Setting up a Waffle project
Creating issues for your Local Weather app
Crafting UI elements using components and interfaces
Adding an Angular component
Define your model using interfaces
Using Angular Services and HttpClient to retrieve data
Creating a new Angular Service
Inject dependencies
Discover OpenWeatherMap APIs
Storing environment variables
Implementing an HTTP GET operation
Retrieving service data from a component
Transform data using RxJS
Understanding Reactive programming
Implementing Reactive transformations
Summary
Prepare Angular App for Production Release
Angular unit tests
Unit test execution
Declarations
Providers
Imports
Test doubles
Jasmine specs
Angular e2e tests
e2e test execution
e2e spec
Troubleshooting common Angular errors
Debugging with Chrome Developer Tools
Optimizing Chrome Dev Tools
Troubleshooting network issues
Investigating console errors
Karma, Jasmine, and Unit Testing errors
NetworkError
Generic ErrorEvents
Debugging with Visual Studio Code
Null guarding in Angular
Property initialization
Safe navigation operator
Null guarding with *ngIf
Containerizing the app using Docker
Installing Docker
Setting up Docker scripts
Docker extension in VS Code
NPM Scripts in VS Code
Deploying containerized app
Zeit Now
Configuring the Now CLI tool
Deploying
Summary
Staying Up to Date with Angular Updates
A brief history of web frameworks
Updating Node
n - Node version manager for macOS
Updating npm and Global npm packages
Global Npm packages
Npm fails to install a global tool on Windows
Updating Angular
Angular update guide
Take stock of your current version
Using Angular Update Guide
Updating your Angular app
Pre-upgrade checklist
Before updating
During the Update
Incompatible peer dependencies
Continuing the update
After the update
Post Update Checklist
Manual update
Testing performance
Addressing security vulnerabilities
Updating your web server
Updating Docker image
Summary
Enhance Angular App with Angular Material
Angular Material
Angular Material setup and performance
Installing Angular Material
Automatically
Manually
Understanding Material's components
Manually configuring Angular Material
Importing modules
Importing theme
Adding Material Icon font
Angular Flex Layout
Responsive layouts
Installing Angular Flex Layout
Layout basics
Flex Layout APIs for DOM containers
Flex Layout APIs for DOM elements
Flex Layout APIs for any element
Adding Material Components to your app
Angular Material schematics
Modifying landing page with Material Toolbar
Representing weather in Material Card
Accessibility
Card header and content
Material typography
Applying typography
Updating the tagline as center-aligned caption
Updating Current Weather card layout
Implementing Layout Scaffolding
Aligning elements
Styling elements
Fine-tuning styles
Tweaking to match design
Updating unit tests
Custom themes
Advanced themes
Updating Angular Material
Take stock of your current versions
Check on the latest available versions
Updating Angular Material
Summary
Reactive Forms and Component Interaction
Interactive prototype
MockFlow WireFramePro
Building the mock-up
Home screen
Search results
Settings pane
Adding interactivity
Exporting the functional prototype
Searching with user input
Adding Angular Reactive Forms
Adding and verifying components
Adding search to weather service
Implementing search
Limiting user inputs with throttle/debounce
Implementing input validation and error messaging
Template driven forms with two-way binding
Enabling component interaction
Global events
Child-parent relationships with event emitters
Parent-child relationships with input binding
Sibling interactions with subjects
Summary
Create a Router-First Line-of-Business App
Angular cheat sheet
Binding
Built-in directives
Common pipes
Starter commands, major components, and CLI scaffolds
Configure Angular CLI autocomplete
Router-first architecture
Creating LemonMart
Creating a Router-first app
Configuring Angular.json and Package.json
Configuring Material and Styles
Designing LemonMart
Identifying user roles
Identifying high-level modules with site map
Generating router-enabled modules
Designing the home route
Setting up default routes
RouterLink
Router outlet
Branding, Custom, and Material Icons
Branding
Color palette
Implementing browser manifest and icons
Custom icons
Material icons
Angular Augury
Component Tree
Break point debugging
Router Tree
NgModules
Submodules with lazy loading
Configuring submodules with components and routes
Eager loading
Lazy loading
Completing the walking skeleton
Manager module
User module
POS and inventory modules
POS module
Inventory module
Inspect router tree
Common Testing Module
Summary
Continuous Integration and API Design
Continuous Integration
Containerizing build environment
Builder
Debugging build environment
Tester
Configuring a headless browser for Angular
Configuring testing environment
Web server
CircleCI
Code coverage report
API design
Designing around major data components
Defining entities
Swagger
Defining a Swagger YAML file
Creating a Swagger server
OpenAPI 3.0 with unofficial tooling
Swagger 2.0 with official tooling
Enable Cross-Origin Resource Sharing (CORS)
Verifying and publishing Swagger server
Summary
Design Authentication and Authorization
Wrapping up mock-ups
Design authentication and authorization workflow
Add auth service
Implement a basic authentication service
Implementing the login component
Conditional navigation
Common validations
UI service
Caching with cookie and localStorage
JSON Web Token life cycle
HTTP interceptor
Side navigation
Log out
Role-based routing after login
Router Guards
Auth Guard
Auth Service Fake and Common Testing Providers
Summary
Angular App Design and Recipes
User class and object-oriented programming
Reusing components
User service with caching, GET and POST
User profile with multi-step auth-enabled responsive forms
Form groups
Stepper and responsive layout
Calculated properties and DatePicker
Type ahead support
Dynamic form arrays
ViewUser component
Review component and Save form
Resolve guard
Reusable component with binding and route data
Master/detail view auxiliary routes
Data table with pagination
Updating Unit Tests
Summary
Highly-Available Cloud Infrastructure on AWS
Creating a secure AWS account
Securing secrets
Right-sizing infrastructure
Optimizing instance
Simple load testing
Deploy to AWS ECS Fargate
Configuring ECS Fargate
Creating a Fargate Cluster
Creating container repository
Creating task definition
Creating elastic load balancer
Creating cluster service
Configuring the DNS
Getting the DNS Name
Prep Angular app
Adding npm Scripts for AWS
Publish
AWS Billing
Summary
Google Analytics and Advanced Cloud Ops
Collecting Analytics
Adding Google Tag Manager to Angular App
Set up Google Tag Manager
Setting up Google Analytics
Configuring Google Analytics Tag in Tag Manager
Budgeting and scaling
Calculating per user cost
Advanced load testing
Reliable Cloud Scaling
Cost per user in a scalable environment
Calculating target server utilization
Pre-scheduled provisioning
Blue-Green deployments
Revising estimates with metrics
Measuring actual use
Creating a custom event
Adding custom events in Angular
Advanced Analytics events
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Welcome! If you are looking to learn about and get good at Angular development, you're in the right place. This book will aim to instill an Agile and DevOps mindset in you so that you confidently create reliable and flexible solutions. Whether you consider yourself a freelancer developing software for small businesses, a full-stack developer, an enterprise developer, or a web developer, what you need to know to design, architect, develop, maintain, deliver, and deploy a web application and the best practices and patterns you need to apply to achieve those things don't vary all that much. If you're delivering an application to an audience of users, in a sense, you are a full-stack developer, since you must be aware of a lot of server technologies. In fact, if you master how to deliver Angular applications using TypeScript, it won't be difficult for you to write your own RESTful APIs using Node.js, Express.js, and TypeScript, but that is beyond the scope of this book.
By some definitions, a full-stack developer needs to know everything from catering to international copyright law to successfully creating and operating an application on today's web. If you're an entrepreneur, in a sense, this is true. However, in this book, your culinary skills and your law degree do not apply. This book assumes that you already know how to write a RESTful API with the tech stack of your choice, and if not, fear not! You can still benefit and understand how to work with RESTful APIs.
This book is for beginners and experienced developers alike who are looking to learn Angular or web development in general. If you are an Angular developer, you will be exposed to the entire gamut of designing and deploying an Angular application to production. You will learn about Angular patterns that are easy to understand and teach others. If you are a freelancer, you will pick up effective tools and technologies to deliver your Angular app in a secure, confident and reliable way. If you an enterprise developer, you will learn patterns and practices to write Angular applications with a scalable architecture.
Chapter 1, Setting Up Your Development Environment, goes over a scriptable way to set up your environment.
Chapter 2, Create a Local Weather Web Application, introduces the Kanban method of software development with easy-to-use design tools used to communicate ideas. It also covers Angular fundamentals, unit testing, and leveraging CLI tools to maximize your impact.
Chapter 3, Prepare Angular App for Production Release, covers how to troubleshoot your Angular app, and using containerization with Docker to enable cloud deployments.
Chapter 4, Staying Up to Date with Angular Updates, goes over strategies and the reasons for keeping your development tools and environment up to date.
Chapter 5, Enhance Angular App with Angular Material, introduces you to Angular material and explains how to use it to build great-looking apps.
Chapter 6, Reactive Forms and Component Interaction, teaches you to become comfortable using Angular forms and reactive programming using RxJS.
Chapter 7, Create a Router-First Line-of-Business App, focuses on the Router-first architecture, a seven-step approach to the design and development of mid-to-large applications.
Chapter 8, Continuous Integration and API Design, goes over continuous integration using CircleCI and early integration with backend APIs using Swagger.
Chapter 9, Design Authentication and Authorization, dives into authentication- and authorization-related patterns in Angular and RESTful applications.
Chapter 10, Angular App Design and Recipes, contains recipes commonly needed for line-of-business applications.
Chapter 11, Highly-Available Cloud Infrastructure on AWS, moves beyond application features to go over provisioning a highly-available cloud infrastructure on AWS.
Chapter 12, Google Analytics and Advanced Cloud Ops, goes over the nuances of owning, operating, and optimizing your cloud infrastructure, and using Google Analytics to capture user behavior.
You should already be familiar with full-stack web development
Follow the book in the published order, coding your solution alongside the content in each chapter
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 hosted on GitHub at https://github.com/PacktPublishing/Angular-6-for-Enterprise-Ready-Web-Applications.
The code bundle for the book is also hosted on Author's GitHub repository at https://github.com/duluca/local-weather-app and https://github.com/duluca/lemon-mart.
We also have other code bundles from our rich catalog of books and videos available at https://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: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."
A block of code is set as follows:
{ "name"
:
"local-weather-app"
,
"version"
:
"0.0.0"
,
"license"
:
"MIT"
,
...
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
"scripts": { "ng": "ng", "start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint", "e2e": "ng e2e" },
Any cross-platform or macOS specific command-line input or output is written as follows:
$ brew tap caskroom/cask
Windows specific command-line input or output is written as follows:
PS> Set-ExecutionPolicy
AllSigned; iex ((
New-Object
System.Net.WebClient).DownloadString(
'https://chocolatey.org/install.ps1'
))
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: "Launch the Start menu."
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.
Let's start with questioning the premise of this entire book, Angular itself. Why learn Angular, but not React, Vue, or some other framework? First, I won't be making an argument against learning any new tool. I believe that every tool has its place and purpose. Becoming somewhat proficient in React or Vue can only help further your understanding of Angular. Single Page Application (SPA) frameworks such as Backbone or Angular have grabbed my full attention since 2012, when I realized server-side rendered templates are impossible to maintain and cause very expensive rewrites of software systems. If you're intent on creating maintainable software, decoupling of APIs and business logic from the user interface (UI) is the prime directive you must abide by.
The question is, why get good at Angular? I have found that Angular neatly fits the Pareto principal. It has become a mature and evolving platform, allowing you to achieve 80% of tasks with 20% of the effort. Furthermore, starting with version 4, in Long Term Support (LTS) until October 2018, every major release is supported for 18 months, creating a continuum of learning, staying up-to-date and deprecating old features. From the perspective of a full-stack developer, this continuum is invaluable, since your skills and training will remain useful and fresh for many years to come.
This first chapter will help you and your team members create a consistent development environment. It can be tough for beginners to create the correct development environment, which is essential for a frustration-free development experience. For seasoned developers and teams, achieving a consistent and minimal development environment remains a challenge. Once achieved, such a development environment helps avoid many IT-related issues, including ongoing maintenance, licensing, and upgrade costs.
Instructions on installing GitHub Desktop, Node.js, Angular CLI, and Docker will be a good reference from absolute beginners all the way to seasoned teams, along with strategies to automate and ensure the correct and consistent configuration of your development environment.
Feel free to skip this chapter if you already have a robust development environment setup; however, beware that some of the environmental assumptions declared in this chapter may result in some instructions not working for you in later chapters. Come back to this chapter as a reference if you run into issues or need to help a colleague, pupil, or friend set up their development environment.
In this chapter, you will learn the following:
Working with CLI package managers to install and update software:
Chocolatey on Windows 10
Homebrew on macOS X
Using scripting to automate installation using:
Powershell on Windows 10
Bash on macOS X
Achieving a consistent and cross-platform development environment
You should be familiar with these:
JavaScript ES2015+
Frontend development basics
RESTful APIs
The supported operating system are as follows:
Windows 10 Pro v1703+ with PowerShell v5.1+
macOS Sierra v10.12.6+ with Terminal (Bash or Oh My Zsh)
Most of the suggested software also works on Linux systems, but your experience may vary
The suggested cross-platform software is as follows:
Node 8.10+ (except non-LTS versions)
npm 5.7.1+
GitHub Desktop 1.0.0+
Visual Studio Code v1.16.0+
Google Chrome 64+
Installing software through a Graphical User Interface (GUI) is slow and difficult to automate. As a full-stack developer, whether you're a Windows or a Mac user, you must rely on Command-Line Interface (CLI) package managers to efficiently install and configure the software you will be depending on. Remember, anything that can be expressed as a CLI command can also be automated.
Chocolatey is a CLI-based package manager for Windows, which can be used for automated software installation. To install Chocolatey on Windows, you will need to run an elevated command shell:
Launch the
Start
menu
Start typing in
PowerShell
You should see
Windows PowerShell Desktop App
as a search result
Right-click on
Windows
PowerShell
and select
Run as Administrator
This will trigger a
User Account Control
(UAC) warning; select
Yes
to continue
Execute the following command in
PowerShell
to install the Chocolatey package manager:
PS> Set-ExecutionPolicy
AllSigned; iex ((
New-Object
System.Net.WebClient).DownloadString(
'https://chocolatey.org/install.ps1'
))
Verify your Chocolatey installation by executing
choco
You should see a similar output, as shown in the following screenshot:
For more information, refer to:https://chocolatey.org/install.
Homebrew is a CLI-based package manager for macOS, which can be used for automated software installation. To install Homebrew on macOS, you will need to run a command shell.
Launch
Spotlight Search
with
⌘ + Space
Type in
terminal
Execute the following command in the Terminal to install the Homebrew package manager:
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Verify your Homebrew installation by executing
brew
You should see a similar output, as follows:
To enable access to additional software, execute the following command:
$ brew tap caskroom/cask
For more information, check out:https://brew.sh/.
This section aims to establish a best practice Git configuration that's suitable for the widest audience possible. In order to make the best use of this section and subsequent chapters of this book, it is presumed that you, the reader, have the following prerequisites fulfilled:
An understanding of what Source Code Management and Git are
Create a free account on
GitHub.com
If you are a Git user, chances are that you also use an online repository, such as GitHub, Bitbucket, or GitLab. Each repository has a free-tier for open source projects, coupled with robust websites with varying feature sets, including on-premise Enterprise options that you can pay for. GitHub, with 38+ million repositories hosted in 2016, is by far the most popular online repository. GitHub is widely considered a baseline utility that will never go offline by the community.
Over time, GitHub has added many rich features that have transformed it from a mere repository to an online platform. Throughout this book, I’ll be referencing GitHub features and functionalities, so you can leverage its capabilities to transform the way you develop, maintain, and release software.
It is true that the Git CLI tool is powerful, and you will be just fine if you stick to it. However, we, full-stack developers, are worried about a variety of concerns. In your rush to complete the task at hand, you can easily ruin your and sometimes your team's day, by following bad or incomplete advice.
See the following screenshot of such advice from StackOverflow (http://stackoverflow.com/questions/1125968/force-git-to-overwrite-local-files-on-pull):
If you execute the preceding command, be prepared to lose uncommitted local changes. Unfortunately, novice users have a tendency to follow the simplest and most direct instructions, potentially leading to lost work. If you think your past commits are safe, think twice! When it comes to Git, if you can imagine it, it can be done through the CLI.
Thankfully, with GitHub, you can protect branches and implement the GitHub workflow, which entails branching, committing, merging, updating, and submitting pull requests. The protections and the workflow help prevent harmful Git commands from making irreversible changes and enable a level of quality control so that your team remains productive. Performing all of these actions through the CLI, especially when there are merge conflicts, can get complicated and tedious.
For a more in-depth understanding of the benefits and pitfalls of Git and GitHub, you can read my 2016 article on the topic at: Bit.ly/InDepthGitHub.
GitHub Desktop provides an easy-to-use GUI to execute the GitHub workflow, in a manner that is consistent across Windows and macOS. Consistency is highly valuable when on-boarding new or junior team members or if you're not a frequent contributor to the code base.
Execute the installation command:
For Windows:
PS> choco install git github-desktop -y
For macOS:
$ brew install git && brew cask install github-desktop
Verify your Git installation by executing
git --version
and observe the version number returned
Verify your GitHub Desktop installation by launching the application
Sign in to
https://github.com/
on GitHub Desktop
Once you have created a repository, you can launch the application from your Terminal by executing this:
$ github path/to/repo
If you are already on the correct folder, you can type in the following command instead:
$ github .
This section aims to establish a best practice JavaScript development environment. To make the best use of this book, it is presumed that you have the following prerequisites fulfilled:
Awareness of the modern JavaScript ecosystem and tools
NodeJS's site:
https://nodejs.org
Npm's site:
https://www.npmjs.com
Angular's site:
https://angular.io
Legacy AngularJS's site:
https://angularjs.org/
Yarn's site:
https://yarnpkg.com
React's site:
https://facebook.github.io/react
Node.js is JavaScript that runs anywhere. It's an open source project that aimed to run JavaScript on the server, built on Google Chrome's V8 JavaScript engine. In late 2015, Node.js stabilized and announced enterprise-friendly 18 month LTS cycles that brought predictability and stability to the platform, paired with a more frequently updated, but more experimental, Latest branch. Node also ships bundled with npm, the Node package manager, and as of 2018, npm is the largest repository of JavaScript packages in the world.
For a more detailed look into Node's history, read my two-part article on Node at: Bit.ly/NodeJSHistory.
If you installed Node.js before, when installing a new version of Node using choco or brew, ensure that you read the command outputs carefully. Your package manager may return caveats or additional instructions to follow, so you can successfully complete the installation.
It is also highly likely that your system or folder permissions have been edited manually in the past, which may interfere with a frustration-free operation of Node. If the following commands do not resolve your issues, use the GUI installer from Node's site as a last resort.
Regardless, you must take care to uninstall all global tools that were installed using npm -g previously. With every major Node version, there's a chance that native bindings between your tool and Node have been invalidated. Further, global tools rapidly fall out of date and project-specific tools quick go out of sync. As a result, installing tools globally is now an anti-pattern that has been replaced with better techniques, which are covered in the next section and under the Angular CLI section in Chapter 2, Create a Local Weather Web Application.
This book will presume that you're using Node 8.4 or a later version. Odd numbered versions of Node are not meant to be long lived. 6.x.x, 8.x.x, 10.x.x, and so on are okay, but avoid 7.x.x, 9.x.x, and so on, at all costs.
Execute the installation command:
For Windows:
PS> choco install nodejs-lts -y
For macOS:
$ brew install node@8
Verify installation of Node by executing
node -v
Verify npm by executing
npm -v
The npm repository contains numerous useful and mature CLI commands that are often cross-platform. Listed here are the ones I rely on frequently and choose to install globally for performance reasons:
npx
:
Executes CLI tools by downloading the latest version on demand or project-specific local
node_modules
folder. It ships with npm 5 and will allow you to run code generators that frequently update without a global install.
rimraf
: The Unix command
rm -rf
, but works on Windows as well. Very useful in deleting
the
node_modules
folder, especially when Windows is unable to do so due to the nested folder structure.
npm-update
: Analyzes your project folder and reports on which package have newer versions or not, with the option to be able to update all of them, if you so wish.
n
: Dead easy to tool to switch between versions of Node quickly, without having to remember the specific version number. Unfortunately, it only works on macOS/Linux.
http-server
: Sim
ple, zero-configuration command-line HTTP server, which is a great way to locally test static HTML/CSS pages or even the
dist
folder of your Angular or React project.
npm-windows-upgrade
: Neces
sary to upgrade npm on Windows.
Visual Studio Code (VS Code) is one of the best code editors/IDEs out there. It's free and it's cross-platform. The remarkable thing is that VS Code has the lightning fast performance of a code editor, think NotePad++ or Sublime Text, but the feature set and conveniences of costly IDEs, think Visual Studio or WebStorm. For JavaScript development, this speed is essential and is a tremendous quality-of-life improvement for a developer, who frequently switches back and forth between different projects. VS Code brings together an integrated terminal, easy-to-use extension system, transparent settings, excellent search and replace functionalities, and, in my opinion, the best Node.js debugger that exists.
For Angular development, this book will be leveraging VS Code. It is highly recommended that you also use VS Code.
Execute the installation command:
For Windows:
PS> choco install VisualStudioCode -y
For macOS:
$ brew cask install visual-studio-code
One of the best features of Visual Studio Code is that you can also launch it from the CLI. If you're in a folder that you'd like to be editing, simply execute code . or a particular file by executing code ~/.bashrc or code readme.md.
Verify install by
launching Visual Studio Code
Navigate to a folder and execute
code .
This will open up a new VS Code window with the
Explorer
displaying the contents of the current folder
For more information, refer to https://code.visualstudio.com.
At the beginning of the chapter, I proclaimed anything that can be expressed as a CLI command can also be automated. Throughout the setup process, we have ensured that every tool being used was set up and their functionality verifiable through a CLI command. This means we can easily create a PowerShell or bash script to string these commands together and ease the task of setting up and verifying new environments. In fact, I have created a rudimentary implementation of these scripts, which you may download from the Chapter 1 folder of the GitHub Repository for this book:
Navigate to
https://github.com/duluca/web-dev-environment-setup
to find the scripts
Execute
install-windows-deps.ps1
in
PowerShell
to install and verify dependencies on Windows
Execute
install-mac-deps.sh
in
Terminal
to install and verify dependencies on macOS
The harsh reality is that these scripts do not represent a very capable or resilient solution. Scripts can't be executed or managed remotely, and they can't easily recover from errors or survive machine boot cycles. In addition, your IT requirements may be above and beyond what is covered here.
If you deal with large teams and frequent turnover, an automation tool will pay dividends handsomely, whereas if you're on your own or part of a smaller, stable team, it will be vastly overkill. I encourage you to explore tools such as Puppet, Chef, Ansible, and Vagrant to help you decide which one may best fit your needs or if a simple script is just good enough.
In this chapter, you mastered the use of CLI-based package managers for both Windows and macOS to speed up and automate the set up of development environments for you and your colleagues. By reducing variance from one developer's environment to the next, your team can overcome any individual configuration issue more easily and remain focused on the execution of the task at hand more often. With a collective understanding of a common environment, no single individual on the team will carry the burden of having to help troubleshoot everyone else's issues. As a result, your team will be more productive. By leveraging more sophisticated and resilient tools, mid-to-large sized organizations will be able to achieve great savings in their IT budgets.
In the next chapter, you will become familiar with the new Angular platform, optimize your web development environment, leverage Kanban using Waffle and GitHub issues, learn Angular fundamentals to build a simple web app with a full-stack architecture in mind, and get introduced to reactive programming with RxJS.
The article on Automating the Setup of the Local Developer Machine by Vishwas Parameshwarappa is a great place to start for using Vagrant. You can find the article at Red-gate.com/simple-talk/sysadmin/general/automating-setup-local-developer-machine.
In this chapter, we will be designing and building a simple Local Weather app with Angular and a third-party web API, using an iterative development methodology. You will focus on delivering value first, while learning about the nuances and optimal ways of using Angular, TypeScript, Visual Studio Code, Reactive Programming, and RxJS. Before we dive into coding, we will go over the philosophy behind Angular and ensure that your development environment is optimized and can enable collaboration and effortless information radiation.
Each section of this chapter will introduce you to new concepts, best practices, and optimal ways of leveraging these technologies and cover the bases to close any knowledge gaps you may have about web and modern JavaScript development basics.
In this chapter, you will learn Angular fundamentals to build a simple web app and become familiar with the new Angular platform and full-stack architecture.
In this chapter, you will learn the following:
Get introduced to Angular and the philosophy behind it
Configuring a repository with an optimal folder structure for full-stack development
Using Angular CLI to generate your Angular web application
Optimizing Visual Code for Angular & TypeScript development
Planning out your roadmap using Waffle as a GitHub-connected Kanban board
Crafting a new UI element to display current weather information using components and interfaces
Using Angular Services and HttpClient to retrieve data from OpenWeatherMap APIs
Leveraging observable streams to transform data using RxJS
The code samples provided in this book require Angular version 5 and 6. Angular 5 code is runtime compatible with Angular 6. Angular 6 will be supported in LTS until October 2019. The most up-to-date versions of the code repositories may be found at the following:
For Chapters 2 to 6, LocalCast Weather, at:
Github.com/duluca/local-weather-app
For Chapters 7 to 12, LemonMart, at:
Github.com/duluca/lemon-mart
Angular is an open source project maintained by Google and a community of developers. The new Angular platform is vastly different from the legacy framework you may have used in the past. A collaboration with Microsoft makes TypeScript, which is a superset of JavaScript, the default development language, enabling developers to target legacy browsers such as Internet Explorer 11, while writing modern JavaScript code that is supported in evergreen browsers such as Chrome, Firefox, and Edge. The legacy versions of Angular, versions in the 1.x.x range, are now referred to as AngularJS. Version 2.0.0 and higher versions are simply called Angular. Where AngularJS is a monolithic JavaScript Single Page Application (SPA) framework, Angular is a platform that is capable of targeting browsers, hybrid-mobile frameworks, desktop applications, and server-side rendered views.
Each minor version increment in AngularJS meant risky updates with costly deprecations and major new features delivered at uncertain intervals. This led to an unpredictable, ever evolving framework with seemingly no guiding hand to carry code bases forward. If you used AngularJS, you likely got stuck on a particular version, because the specific architecture of your code base made it very difficult to move to a new version. In the spring/summer of 2018, the last major update to AngularJS will be released with version 1.7. This release will mark the beginning of the end for the legacy framework, with a planned end-of-life in July 2021.
Angular improves upon AngularJS in every way imaginable. The platform follows semver, as defined at https://semver.org/, where minor version increments denote new feature additions and potential deprecation notices for the second next major version, but no breaking changes. Furthermore, the Angular team at Google has committed to a deterministic release schedule for major version increments to be released every 6 months. After this 6-month development window, starting with Angular 4,all major releases receive long-term support (LTS) with bug fixes and security patches for an additional 12 months. From release to end-of-life, each major version is supported for 18 months. Refer to the following chart for the tentative release and support schedule for AngularJS and Angular:
So, what does this mean for you? You can be confident that the code you write in Angular will be supported and backwards compatible for an approximate time frame of 24 months, even if you make no changes to it. So, if you wrote an Angular app in version 4 in April 2017, your code is now runtime compatible with Angular 5, which itself is supported until April 2019. In order to upgrade your Angular 4 code to Angular 6, you will need to ensure that you're not using any of the deprecated APIs that were announced as deprecated in Angular 5. In reality, the deprecations are minor and unless you are working with low-level APIs for a highly specialized user experience, the time and effort it takes to update your code base should be minimal. However, this is a promise made by Google and not a contract. The Angular team has a major incentive to ensure backwards compatibility, because Google runs around 600+ Angular apps with a single version of Angular active at any one time throughout the organization. This means, by the time you read this, all of those 600+ apps will be running in Angular 6. You may think Google has infinite resources to make this happen, but like any other organization, they too have limited resources and not every app is actively maintained with a dedicated team. This means the Angular team must ensure compatibility through automated tests and make it as painless as possible to move through major releases going forward. In Angular 6, the update process was made much easier with the introduction of ng update. In the future, the team will release automated CLI tools to make upgrades of deprecated functionality a reasonable endeavor.
This is great news for developers and organizations alike. Now, instead of being perpetually stuck on a legacy version of Angular, you can actually plan and allocate the necessary resources to keep moving your application to the future without costly rewrites. As I wrote in a 2017 blog post, The Best New Feature of Angular 4, at bit.ly/NgBestFeature, the message is clear:
So, why does Google (Angular) and Microsoft (TypeScript, Visual Studio Code) give away such technologies for free? There are multiple reasons, some including demonstration of technical proves to retain and attract talent, proving and debugging new ideas and tools with millions of developers at scale, and ultimately allowing developers to more easily create great web experiences that ultimately drive more business for Google and Microsoft. I personally don't see any nefarious intent here and welcome open, mature, and high-quality tools that I can tinker with and bend to my own will, if necessary, and not have to pay for a support contract for a proprietary piece of tech.
The philosophy behind Angular is to err on the side of configuration over convention. Convention-based frameworks, although may seem elegant from the outside, make it really difficult for newcomers to pick up the framework. Configuration-based frameworks, however, aim to expose their inner workings through explicit configuration elements and hooks, where you can attach your custom behavior to the framework. In essence, Angular tries to be non-magical, where AngularJS was a lot of magic.
This results in a lot of verbose coding. This is a good thing. Terse code is the enemy of maintainability, only benefiting the original author. However, as Andy Hunt and David Thomas put it in the Pragmatic Programmer,
Verbose, decoupled, cohesive, and encapsulated code is the key to future proofing your code. Angular, through its various mechanisms, enables the proper execution of these concepts. It gets rid of many custom conventions invented in AngularJS, such as ng-click, and introduces a more intuitive language that builds on the existing HTML elements and properties. As a result, ng-click becomes (click), extending HTML rather than replacing it.
Most, if not all, of the content, patterns, and practices in this book are compatible with Angular 4 and up. Angular 6 is the latest version of Angular, which brings a lot of under-the-cover improvements to the platform and overall stability and cohesion across the ecosystem. The development experience is being vastly improved with additional CLI tools that make it easier to update versions of packages and faster build times to improve your code-build-view feedback cycle. With Angular 6, all platform tools are version synced to 6.0, making it easier to reason about the ecosystem. In the following chart, you can see how this makes it easier to communicate tooling compatibility:
Previously
With v6
CLI
1.7
6.0
Angular
5.2.10
6.0
Material
5.2.4
6.0
Angular CLI 6.0 comes with major new capabilities, such as ng update and ng add commands; ng update makes it much easier to update your version of Angular, npm dependencies, RxJS, and Angular Material, including some deterministic code rewriting capabilities to apply name changes to APIs or functions. The topic of updating your version of Angular is covered in depth in Chapter 4, Staying Up to Date with Angular Updates. ng add brings schematics support to the Angular CLI. With schematics, you can write custom code to add new capabilities to an Angular app, adding any dependencies, boilerplate configuration code, or scaffolding. A great example is to be able to add Angular Material to your project by executing ng add @angular/material. The topic of adding Angular Material to your project is covered in depth in Chapter 5, Enhance Angular App with Angular Material. A standalone Material Update tool aims to make Angular Material updates less painful, found at Github.com/angular/material-update-tool, but expect this functionality to be merged into ng update. Further schematics can bring their own generate commands to CLI, making your life easier and code base more consistent over time. In addition, version 4 of Webpack is configured to build your Angular application into smaller modules with scope hosting, shortening the first-paint time of your app.
The major theme of Angular 6 is under-the-hood performance improvements and Custom Elements support. Version 6 improves upon v5 in terms of the base bundle size by 12% at 65 KB, which improves load times a whopping 21-40% from Fast 3G to Fiber connections. As your applications grows, Angular takes advantage of a better tree-shaking technique to further prune unused code out of your final deliverable. Speed is a UX feature in Angular 6. This is accomplished with better support for Angular Component Development Kit (CDK), Angular Material, Animations, and i18n. Angular Universal allows for server-side assisted fast startup times, and Angular Progressive Web App (PWA) support takes advantage of native platform features such as caching and offline, so in subsequent visits, your app remains fast. RxJS 6 support allows for the tree-shakeable pipe command, reducing bundle sizes more often, and fix the behavior of throttle as I caution you in Chapter 6, Reactive Forms and Component Interaction, among numerous bug fixes and performance improvements. TypeScript 2.7 brings in better support for importing different types of JavaScript packages and more advanced features to catch coding errors during build time.
Custom Elements support, part of the Web Components spec, is huge. With Angular Elements, you can code an Angular component and reuse that component in any other web application using any web technology, in essence declaring your very own custom HTML element. These custom elements would be cross-compatible with any HTML-based tool chain, including other web application libraries or frameworks.
