Book Image

Angular for Enterprise-Ready Web Applications - Second Edition

By : Doguhan Uluca
Book Image

Angular for Enterprise-Ready Web Applications - Second Edition

By: Doguhan Uluca

Overview of this book

This second edition of Angular for Enterprise-Ready Web Applications is updated with in-depth coverage of the evergreen Angular platform. You’ll start by mastering Angular programming fundamentals. Using the Kanban method and GitHub tools, you’ll build great-looking apps with Angular Material and also leverage reactive programming patterns with RxJS, discover the flux pattern with NgRx, become familiar with automated testing, utilize continuous integration using CircleCI, and deploy your app to the cloud using Vercel Now and GCloud. You will then learn how to design and develop line-of-business apps using router-first architecture with observable data anchors, demonstrated through oft-used recipes like master/detail views, and data tables with pagination and forms. Next, you’ll discover robust authentication and authorization design demonstrated via integration with Firebase, API documentation using Swagger, and API implementation using the MEAN stack. Finally, you will learn about DevOps using Docker, build a highly available cloud infrastructure on AWS, capture user behavior with Google Analytics, and perform load testing. By the end of the book, you’ll be familiar with the entire gamut of modern web development and full-stack architecture, learning patterns and practices to be successful as an individual developer on the web or as a team in the enterprise.
Table of Contents (19 chapters)
15
Another Book You May Enjoy
16
Index

Installing development tools

In this section, you'll install all the development tools you need to start developing a web application. Git and GitHub Desktop establish a source code repository on your machine and allow you to sync your code with a remote repository. Node.js is a JavaScript runtime for your PC and it ships with the Node Package Manager or npm. Npm manages third-party source code including Angular. Visual Studio Code is an Integrated Development Environment or IDE.

To automatically install all of the web development tools required for this book, execute the following commands for your OS to configure your environment.

On Windows PowerShell, execute:

PS> Install-Script -Name setup-windows-dev-env
PS> setup-windows-dev-env.ps1

On MacOS Terminal, execute:

$> bash <(wget -O - https://git.io/JvHi1)

For more information refer to https://github.com/duluca/web-dev-environment-setup.

Once you install your IDE, you're ready to start development. This section also contains instructions to install Docker, a lightweight containerization platform, and configure various cloud services. These tools will become relevant in later chapters. If you want a quicker start to your Angular adventure, you can skip them for now.

Git and GitHub Desktop

This section aims to establish a best practice Git configuration that's suitable for the broadest audience possible. To make the best use of this section and subsequent chapters of this book, I presume you have the following prerequisites fulfilled:

  • An understanding of what source code management and Git actually are
  • A free account created on GitHub.com

Why use GitHub?

If you are a Git user, the 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 different 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. It is widely considered a baseline utility that never goes 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.

Why use GitHub Desktop?

The Git CLI tool is indeed 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 a rush to complete the task at hand, you can easily ruin your, and sometimes your team's, day by following incorrect or incomplete advice.

See the following screenshot for an example of such advice from Stack Overflow (http://stackoverflow.com/questions/1125968/force-git-to-overwrite-local-files-on-pull):

Figure 2.3: An example of a command not to run blindly

If you execute the preceding command, be prepared to lose uncommitted local changes. Unfortunately, novice users tend to follow the most straightforward 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.

Note that Git ships with a CLI tool named Git Bash, which is a Unix-based shell that you can use to execute git and other commands. Bash is readily available on Linux and macOS computers. Windows 10 is rapidly improving its terminal support with Windows Subsystem for Linux (WSL) and alias to Unix commands in PowerShell, so the need to use Git Bash on Windows is rapidly disappearing. If you would like to learn more about Git Bash see the tutorial at Atlassian's website at https://www.atlassian.com/git/tutorials/git-bash.

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.

Installing Git and GitHub Desktop

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 onboarding new or junior team members, or if you're not a frequent contributor to the code base. We recommend you install GitHub Desktop 2.2+.

  1. Execute the installation command:

    For Windows:

    PS> choco install git github-desktop -y
    

    For macOS:

    $ brew install git && brew cask install github
    
  2. Verify your Git installation by executing git --version and observe the version number returned

    You need to restart your Terminal after the installation of a new CLI tool. However, you can avoid relaunching your Terminal and save some time by refreshing or sourcing your environment variables. On Windows, execute refreshenv; on macOS, execute source ~/.bashrc or source ~/.zshrc.

  3. Verify your GitHub Desktop installation by launching the application
  4. Sign in to https://github.com/ on GitHub Desktop
  5. Once you have created a repository, you can launch the application from your Terminal by executing this:
    $ github path/to/repo
    
  6. If you are already in the correct folder, you can type in the following command instead:
    $ github .
    

For Windows, on GitHub Desktop launch, if you get stuck on the sign in screen, close the application, relaunch it as an administrator, complete the setup, and then you may use it normally, without having to launch it as an administrator again. For more information, refer to https://desktop.github.com/.

Next, we'll go over several strategies for having a smoother experience with Git by properly registering your GitHub credentials.

Using your GitHub credentials in Git

When you interact with your repository on GitHub, the git command is leveraged by the tools you're using, like your IDE, to push or pull content. To have a smooth experience with Git, it is a good idea to register your GitHub credentials with Git properly.

There are three major strategies to accomplish this:

  1. Configure SSH – which is the best and most secure way to interact with any remote computer system, because no passwords are exchanged. You can follow the latest guide from GitHub to configure SSH at https://help.github.com/articles/connecting-to-github-with-ssh.
  2. Cache your GitHub password in Git – sometimes SSH won't be supported by the tool you use, so you may need to cache your password. You can do so by executing the following command:

    For Windows:

    PS> git config --global credential.helper wincred
    

    For macOS:

    $ git credential-osxkeychain
    $ git config --global credential.helper osxkeychain
    

    For further guidance, refer to the GitHub guide at https://help.github.com/articles/caching-your-github-password-in-git.

  1. Create a personal access token – this is a strategy that falls in between SSH and password usage from a security perspective because SSH keys and tokens can be revoked at any time from GitHub, but once your password is leaked or compromised, you may lose control of everything.

If you're using two-factor authentication, which you absolutely should, then instead of caching your password, you need to create a personal access token at https://github.com/settings/tokens and use the token instead of your password. In Chapter 3, Creating a Basic Angular App, we cover how you can set up a token to work with Visual Studio Code, the preferred IDE for this book.

Check out TJ Holowaychuk's git-extras tool, which can provide repo summary, changelog population, author commit percentage, and more useful information about your repos at https://github.com/tj/git-extras.

Node.js

This section aims to establish a best practice JavaScript development environment. I presume that you have an awareness of the modern JavaScript ecosystem and tools. At a minimum, make sure to familiarize yourself with the following resources:

Node.js is JavaScript that runs anywhere. It's an open source project that aims 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.

You may have heard of Yarn and how it's faster or better than npm. As of npm 5, which ships bundled with Node 8, npm is more feature-rich, easier to use, and on par with Yarn in terms of performance. Yarn is published by Facebook, which also created React. It must be noted that Yarn relies on the npm repository, so whichever tool you use, you get access to the same library of packages.

Existing Node.js installation

If you have 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 the frustration-free operation of Node. If the following commands do not resolve your issues, use the GUI installer from Node's website as a last resort.

To see a list of your global install packages, execute npm list -g --depth=0. To uninstall a global package, execute npm uninstall -g package-name. I would recommend that you uninstall all globally installed packages and restart from scratch with the suggestions provided in the next section.

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 quickly 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 in the Angular CLI section in Chapter 3, Creating a Basic Angular App.

Installing Node.js

This book presumes that you're using Node 12.13 or a later version. Odd-numbered versions of Node are not meant to be long-lived. 8.x.x, 10.x.x, 12.x.x, and so on are okay, but avoid 9.x.x, 11.x.x, and so on, at all costs, as they are meant to be experimental.

  1. Execute the installation command:

    For Windows:

    PS> choco install nodejs-lts -y
    

    For macOS:

    $ brew install node@10
    
  2. Verify the installation of Node by executing node -v
  3. Verify npm by executing npm -v

    Note that on Windows, you should never upgrade your npm version using npm install -g npm, as highlighted in Appendix C, Keeping Angular and Tools Evergreen. You can find this appendix online from https://static.packt-cdn.com/downloads/9781838648800_Appendix_C_Keeping_Angular_and_Tools_Evergreen.pdf or at https://expertlysimple.io/stay-evergreen. It is highly recommended that you use the npm-windows-upgrade npm package.

For this book, make sure that you've got npm v.6.12+. Now, let's go over some handy npm packages you may want to install globally.

Global npm packages

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 the project-specific local node_modules folder. Npx ships with npm 5+ and allows you to run code generators that frequently update without a global install.
  • rimraf: The Unix command rm -rf works on Windows as well. It's very useful for deleting the node_modules folder, especially when Windows is unable to do so due to the nested folder structure.
  • npm-check-updates: Analyzes your project folder and reports on which package has newer versions or not, with the option to be able to update all of them if you so wish. ncu for short.
  • n: A dead easy to tool to switch between versions of Node quickly, without having to remember the specific version number, which works on macOS/Linux. For Windows, you can use the choco package, nvs; both n and nvs are covered in the Appendix C, Keeping Angular and Tools Evergreen.
  • http-server: A simple, 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: Necessary to upgrade npm on Windows.
  • npkill: Easily find and remove old and heavy node_modules folders and reclaim gigabytes of disk space.

    You can use npm-check-updates to keep all of your global packages up to date by executing ncu -g.

If you run into EACCES permissions errors while installing global packages on macOS, refer to the guide from npm at https://docs.npmjs.com/getting-started/fixing-npm-permissions.

Visual Studio Code

Visual Studio Code (VS Code) is one of the best code editors/IDEs out there, built and maintained by Microsoft. It's free and 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 convenience 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.

This book does not require you to use VS Code. If you wish to use another IDE like WebStorm you may do so. WebStorm is a paid product and delivers a great development experience out of the box, whereas VS Code requires a lot of customization. This book offers automated scripts to configure VS Code for an optimal Angular development experience.

You can find more about WebStorm at https://www.jetbrains.com/webstorm.

Installing Visual Studio Code

For Angular development, this book leverages VS Code v1.42+. I highly recommend that you also use the latest version of VS Code.

  1. 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 VS 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.

  2. Verify the installation by launching VS Code
  3. Navigate to a folder and execute code
  4. This opens 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.

With VS Code installed, you're ready to start development. If you want a quicker start to your Angular adventure, skip ahead to the Angular CLI section and refer back to this section when you need Docker and the tools for various cloud services.

Docker

Docker is a lightweight container virtualization platform with workflows and tooling that help manage and deploy applications.

Installing Docker

To be able to build and run containers, you must first install the Docker execution environment on your computer.

Windows support for Docker can be challenging. You must have a PC with a CPU that supports virtualization extensions, which is not a guarantee on laptops. You must also have a Pro version of Windows with Hyper-V enabled. On the flip side, Windows Server has native support for Docker, which is an unprecedented amount of support shown by Microsoft toward the industry initiative to adopt Docker and containerization.

  1. Install Docker by executing the following command:

    For Windows:

    PS> choco install docker docker-for-windows -y
    

    For macOS:

    $ brew install docker
    
  1. Execute docker -v to verify the installation

Cloud services

Throughout the book, we'll use various cloud providers to perform deployments of the apps that you are going to build. Each service ships with a CLI tool that facilities the deployment of your app from your Terminal or a continuous integration (CI) environment in the cloud.

Vercel Now

Vercel Now is a cloud platform for static sites and serverless functions. With a simple CLI command, you host websites and deploy web services instantly. This book leverages a free-tier Vercel Now account.

  1. Create a Vercel Now account at https://vercel.com.
  2. Install the CLI tool by executing:
    $ npm i -g now
    
  3. Verify the installation by executing:
    $ now login
    
  4. Follow the instructions to complete the login process. You should see a message similar to the one that follows:
    > We sent an email to [email protected]. Please follow the steps provided inside it and make sure the security code matches Classical Slow Worm
    √ Email confirmed
    > Congratulations! You are now logged in. In order to deploy something, run `now`
    

For more information, refer to https://vercel.com.

Google Firebase

Firebase is Google's cloud platform tailored for hosting mobile and web apps with authentication, push notifications, cloud functions, databases, machine learning, and analytics support. This book leverages a free-tier Firebase account.

  1. Create a Firebase account at https://firebase.google.com/.
  2. Install the CLI tool by executing:
    $ npm i -g firebase-tools
    
  3. Verify the installation by executing:
    $ firebase login
    
  4. Follow the instructions to complete the login process. You should see a message similar to the one that follows:
    Waiting for authentication...
    +  Success! Logged in as [email protected]
    

For more information, refer to https://firebase.google.com/.

Google Cloud

Google Cloud is Google's world-class cloud infrastructure for enterprises. This book leverages Google Cloud Run for managed container deployments to the cloud. When you first sign up, you may receive free credits to use Google Cloud. However, this is an optional exercise, as you may incur charges while using this service if you forget to tear down your deployment.

  1. Create a Google Cloud account at https://cloud.google.com/
  2. Execute the installation command:

    For Windows:

    PS> choco install gcloudsdk -y
    

    If you have trouble installing gcloudsdk from choco, then try scoop, as mentioned earlier in the chapter. Execute the commands that follow:

    $ scoop bucket add extras
    $ scoop install gcloud
    

    For macOS:

    $ brew install google-cloud-sdk
    
  3. Verify the installation by executing gcloud --version
  4. Execute gcloud init to finish the setup

For more information, refer to https://cloud.google.com/run/.

Amazon Web Services

Amazon Web Services (AWS) is a globally deployed cloud infrastructure provided by Amazon. AWS is a widely popular tool with businesses and governments, making it a lucrative service for IT professionals. Chapter 13, Highly Available Cloud Infrastructure on AWS, goes in-depth on how to work with AWS and perform a scalable container-based deployment.

  1. Execute the installation command:

    For Windows:

    PS> choco upgrade awscli -y
    

    For macOS:

    $ brew install awscli
    $ brew upgrade awscli
    

    Note that running the upgrade command on choco and brew ensures that you have the latest version of any given tool if they were previously installed on your environment.

  2. Verify the installation by executing aws --version

For more information, refer to https://aws.amazon.com/.