MEAN Cookbook - Nicholas McClay - E-Book

MEAN Cookbook E-Book

Nicholas McClay

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

The MEAN Stack is a framework for web application development using JavaScript-based technologies; MongoDB, Express, Angular, and Node.js. If you want to expand your understanding of using JavaScript to produce a fully functional standalone web application, including the web server, user interface, and database, then this book can help guide you through that transition. This book begins by configuring the frontend of the MEAN stack web application using the Angular JavaScript framework. We then implement common user interface enhancements before moving on to configuring the server layer of our MEAN stack web application using Express for our backend APIs. You will learn to configure the database layer of your MEAN stack web application using MongoDB and the Mongoose framework, including modeling relationships between documents. You will explore advanced topics such as optimizing your web application using WebPack as well as the use of automated testing with the Mocha and Chai frameworks. By the end of the book, you should have acquired a level of proficiency that allows you to confidently build a full production-ready and scalable MEAN stack application.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 476

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



MEAN Cookbook
The meanest set of MEAN stack solutions around
Nicholas McClay

BIRMINGHAM - MUMBAI

MEAN Cookbook

Copyright © 2017 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.

First published: September 2017

Production reference: 1250917

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78728-657-3

www.packtpub.com

Credits

Author

Nicholas McClay

Copy Editor

Dhanya Baburaj

Reviewer

Joel Holmes

Project Coordinator

Devanshi Doshi

Commissioning Editor

Ashwin Nair

Proofreader

Safis Editing

Acquisition Editor

Larissa Pinto

Indexer

Pratik Shirodkar

ContentDevelopmentEditor

Onkar Wani

Graphics

Jason Monteiro

Technical Editor

Akhil Nair

Production Coordinator

Shraddha Falebhai

About the Author

Nicholas McClay is a software developer and designer with over a decade of JavaScript experience in both corporate and startup technology companies. He is an avid Node.js and JavaScript enthusiast and the founder of the greater Pittsburgh region’s Node.js and Angular meetups. A self-described user experience developer, he balances using both design and development disciplines to solve problems.

He is a graduate of the Art Institute of Pittsburgh, where he acquired a bachelor's of science degree in Game Art and Design, a passion that springboarded him into a career of interactive experience design.

His previous work experience includes Autodesk, where he worked on next-generation integrated cloud services. His current role is as the UX Lead of Wombat Security Technologies, where he helps bridge the gap between the customers' user experience and the underlying technology and product decisions that deliver it.

He enjoys video games, tinkering and creating things, and lives with his loving wife, son, and daughter in Pittsburgh, Pennsylvania.

Acknowledgement

Writing a book about JavaScript web development wasn't something I was planning, at least not in the manner that it happened.

Like some of my favorite things in life, it was a surprise opportunity, which I feel very lucky to have had.

However, actually making this book was also a lot of hard work, so I want to thank those who helped me do it.

I want to thank Joel Holmes for his careful technical consultation and review for this book as well as the editing and publishing staff at Packt; without your careful attention, this book's content would not have been nearly as good or as readable; it was very much appreciated!

I want to thank my grandfather for introducing me to my passion for technology, and a love of learning new things.

You gave me a great gift that I hope I can teach and share with others, like you did for me.

I also want to thank my mother, who raised me to be creative, curious, and independent. Your son is a huge nerd who wrote a programming book, and he would never have had the talent to pull it off without you.

And finally, I want to thank my wife for supporting me through this whole endeavor and making sure my love of run on sentences didn't contaminate the contents of this book, no matter how much unreasonable stress it might have caused, and also for encouraging me to keep going even when it seemed hard and I wanted to quit; thank you for being my partner though this and every other piece of luck we find together!

About the Reviewer

Joel Holmes (@Joel_Holmes) is a graduate from the University of Pittsburgh and is a full stack developer at Wombat Security Technologies. He enjoys learning new technologies and their applications in business. When not working, he enjoys spending time with his wife, Chelsea, and his two children, Eli and Abel.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com. 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.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787286576. If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Table of Contents

Preface

What this book covers

What you need for this book

Who this book is for

Sections

Getting ready

How to do it…

How it works…

There's more…

Conventions

Reader feedback

Customer support

Downloading the example code

Downloading the color images of this book

Errata

Piracy

Questions

Working with Angular 4

Introduction

Upgrading to Angular 4 using NPM

Getting ready

How to do it...

How it works...

There’s more…

Taking advantage of optional dependencies

Peer dependency warnings after upgrade

Generating a new Angular project using Angular-CLI

Getting ready

How to do it...

How it works...

There's more...

Tips for resolving port collision

Configuring Angular-CLI project settings

How to do it...

Working with generators in Angular-CLI

How to do it...

How it works...

There's more...

Ejecting Angular-CLI from your project

Getting ready

How to do it...

How it works...

Generating new routes in Angular-CLI

Getting ready

How to do it...

How its works...

Defining a home page in your Angular routes

How to do it...

How it works...

There's more...

Handling 404 errors in an Angular project

How to do it...

How it works...

Creating nesting routes in Angular

Getting ready

How to do it...

How it works...

Creating sibling routes in Angular

How to do it...

How it works...

There's more...

Programmatic page redirection in Angular

How to do it...

How it works...

Route preloading with Angular modules

Getting ready

How to do it...

How it works...

Running tests in Angular-CLI

How to do it...

How it works...

Enhancing Your User Interface

Introduction

Configuring Sass in Angular

Getting ready

How to do it...

How it works...

There's more...

Working with Angular component styles

How to do it...

How it works...

Using Sass variables for style reusability

How to do it...

How it works...

There's more...

Using Sass nesting for better style specificity

Getting ready

How to do it...

How it works...

There's more...

Using Sass partials for style organization

Getting ready

How to do it...

How it works...

There's more...

Working with Bootstrap in Sass

How to do it...

How it works...

There's more...

Customizing Bootstrap for Angular

Getting ready

How to do it...

How it works...

There's more...

Using Bootstrap Responsive layouts

Getting ready

How to do it...

How it works...

There's more...

Working with Bootstrap components in Angular

Getting ready

How to do it...

How it works...

There's more...

Working with Font-Awesome icons in Angular

Getting ready

How to do it...

How it works...

There's more...

Internationalization with Angular i18n

Getting ready

How to do it...

How it works...

There's more...

Setting your language with Angular i18n

Getting ready

How to do it...

How it works...

There's more...

How to Localize dates in Angular

How to do it...

How it works...

There's more...

Working with Data

Introduction

Working with actions and events in Angular

Getting ready

How to do it...

How it works...

There's more...

Working with form input and models in Angular

Getting Ready

How to do it...

How it works...

There's more...

Validating data with Angular form properties

Getting Ready

How to do it...

How it works...

There's more...

Creating services for data in Angular

Getting ready

How to do it...

How it works...

There's more...

Using promises to create asynchronous services in Angular

Getting ready

How to do it...

How it works...

There's more...

Retrieving API data using HTTP services in Angular

Getting ready

How to do it...

How it works...

There's more...

Querying API sources using HTTP services in Angular

Getting ready

How to do it...

How it works...

There's more...

Creating Concurrent API requests in Angular

Getting ready

How to do it...

How it works...

Handling API errors and invalid responses in Angular

Getting ready

How to do it...

HTTP service optimization through client-side caching

Getting Ready

How to do it...

How it works...

Using Express Web Server

Introduction

Creating a new Express project with express-generator

Getting ready

How to do it...

How it works...

There's more...

Working with routes in Express

Getting ready

How to do it...

How it works...

There's more...

Serving an Angular web application with Express

Getting ready

How to do it...

How it works...

There's more...

Working with headers in Express

Getting ready

How to do it...

How it works...

There's more...

Working with cookies in Express

Getting ready

How to do it...

How it works...

There's more...

Creating Express middleware for routes

Getting ready

How to do it...

How it works...

There's more...

Logging traffic and activity with Morgan

Getting Ready

How to do it...

How it works...

There's more...

Running your Express web server with Forever

Getting ready

How to do it...

How it works...

There's more...

Securing your Express web server

Getting ready

How to do it...

How it works...

REST APIs and Authentication

Introduction

Building REST APIs with Express

Getting ready

How to do it...

How it works...

There's more...

Configuring JSON API in Express

Getting ready

How to do it...

How it works...

There's more...

Creating a user authentication API in Express

Getting ready

How to do it...

How it works...

There's more...

Building a login page with Angular

Getting ready

How to do it...

How it works...

There's more...

Using JWT authentication with Express and Angular

Getting ready

How to do it...

How it works...

Cloud Service Integrations

Introduction

Uploading large multi-part files with Express

Getting ready

How to do it...

How it works...

There's more...

Uploading images to Cloudinary from Express

Getting ready

How to do it...

How it works...

There's more...

Securing image downloads from Cloudinary

Getting ready

How to do it...

How it works...

There's more...

Resizing images and transformations with Cloudinary

Getting ready

How to do it...

How it works...

There's more...

Working with Stripe payment processor in Express

Getting ready

How to do it...

How it works...

Accepting credit card payments in Angular with Stripe

Getting ready

How to do it...

How it works...

MongoDB and Mongoose

Introduction

How to set up and create a MongoDB database

Getting ready

How to do it...

How it works...

Mongo shell commands

There's more...

Connecting to MongoDB through Mongoose

Getting ready

How to do it...

How it works...

There's more...

Working with data model in MongoDB and Mongoose

How to do it...

How it works...

Mongoose Model API

Mongoose Document API

There's more...

Querying for data using Mongoose query selectors

How to do it...

How it works...

Mongoose Query API

There's more...

Relationships

Introduction

Working with data validations and virtuals in Mongoose

Getting ready

How to do it...

How it works...

SchemaTypes API

There's more...

Creating sub-documents in Mongoose models

Getting ready

How to do it...

How it works...

Using pre-save hooks and custom methods in Mongoose Models

Getting ready

How to do it...

How it works...

Creating embedded documents in MongoDB with objectId

Getting ready

How to do it...

How it works...

Creating relational documents in MongoDB with population

Getting ready

How to do it...

How it works...

There's more...

Document API

Build Systems and Optimizations

Introduction

Using ES6 and Typescript with Express.js and Node.js

Getting ready

How to do it...

How it works...

There's more...

Configuring WebPack for use in Node.js applications

Getting ready

How to do it...

How it works...

There's more...

Optimizing asset delivery with gzip compression in Express

Getting ready

How to do it...

How it works...

There's more...

Optimizing images for delivery with WebPack

Getting ready

How to do it...

How it works...

There's more...

Optimizing Font-Awesome with custom font generation

Getting ready

How to do it...

How it works...

There's more...

Debugging

Introduction

Debugging Node.js using the debug module

Getting ready

How to do it...

How it works...

There's more...

Debugging Node.js using node-inspector in Google Chrome

Getting ready

How to do it...

How it works...

There's more...

Debugging Node.js using JetBrain's WebStorm IDE

Getting ready

How to do it...

How it works...

Production error tracking and debugging with Sentry.io

Getting ready

How to do it...

How it works...

There's more...

Automated Testing

Introduction

Creating unit tests for Node.js using the Mocha testing library

Getting ready

How to do it...

How it works...

There's more...

Creating integration tests for Express REST APIs

Getting ready

How to do it...

How it works...

There's more...

Integrating an ESLint test suite into your Mocha tests

Getting ready

How to do it...

How it works...

There's more...

Cross-browser and device testing with BrowserSync

Getting ready

How to do it...

How it works...

There's more...

Whats new in Angular 4

Angular 4 Improvements and New Features

Packaging and Modules

A newly optimized view engine

Added TypeScript 2.2 support

ngIf directive added support for else statements

Support for assigning local variables

New email form input validator directive

Source maps for generated templates

Angular 4 Deprecations and API Changes

Template tags and attributes have been deprecated

Animations are now an optional library

ngFor class is deprecated

Renderer class is deprecated

Component lifecycle hooks are now interfaces

Preface

This book is a collection of recipes targeted at building modern, all-JavaScript web applications using MongoDB, Express, Angular, and Node.js. Using this MEAN stack, we will configure everything from the frontend of our application's user interface to the backend API and database in an easy-to-follow, project-based fashion. Follow along from the beginning as we build our knowledge of technologies and techniques to scaffold a blogging application, or choose your area of interest and dive deep into the various layers that make up a MEAN stack web application.

You'll find opportunities to learn the latest JavaScript language enhancements, including working with ES2017 and TypeScript to make your application's code more expressive and modular. We'll also explore the latest versions of popular JavaScript frameworks, including the newly released Angular 4, for frontend application development. The recipes and examples in this book also provide detailed references and documentation explaining the various APIs and tools you'll use in your MEAN stack application.

For developers building a MEAN stack experience, this book will call out common pitfalls and fixes for issues you might encounter along the way. Expert developers will find advanced topics that are not often covered in-depth. No matter what your experience level is, you will find practical, realistic examples of building real MEAN stack web applications.

What this book covers

Chapter 1, Working with Angular 4, begins by exploring the frontend layer of our MEAN stack using Angular 4. We'll cover the basics of working with Angular and scaffold out a new application using Angular-CLI. The reader will learn to use Angular-CLI to create components and modules as well as serve the development build of an application to a web browser.

Chapter 2, Enhancing Your User Interface, covers using frontend frameworks such as Sass, Bootstrap, and Font-Awesome. This chapter explores how to add some style to our Angular web application. We'll also look at advanced topics such as component styles and working with Bootstrap components inside an Angular application.

Chapter 3, Working with Data, explains that our Angular application's relationship with data is key to leveraging it in our MEAN stack application. Here, we'll review the basic mechanisms behind data binding inputs and forms within Angular to models. This includes more advanced topics such as working with data services and validating it, using promises to create asynchronous services, retrieving and querying API data, and handling API errors and invalid responses.

Chapter 4, Using Express Web Server, turns our attention to the backend of our MEAN stack web application; we will explore setting up an Express web server using Node.js. This chapter covers the basics of serving assets and routing with Express as well as an exploration of securing an Express web server in production environments.

Chapter 5, REST APIs and Authentication, continues with building our Express web server; we'll build our own APIs for serving resources to our frontend Angular application. The reader will learn how to structure APIs using JSON API to send data and errors to our client. We'll also explore the intricacies of implementing authentication and authorization in our application.

Chapter 6, Cloud Service Integrations, covers the various types of cloud service integrations for our backend Express webserver, including handling images with Cloudinary and implementing a payment gateway using Stripe. We'll also implement a credit card payment user interface with Angular using Stripe.

Chapter 7, MongoDB and Mongoose, explains how to use MongoDB as our database for our Express application. This chapter will cover configuring MongoDB as well as using Mongoose to manage models between an Express web server and a database.

Chapter 8, Relationships, focuses on structuring relationships between our documents in MongoDB. We'll cover the most common types of document relationships, including validation, virutals, subdocuments, and document population with Mongoose.

Chapter 9, Build Systems and Optimizations, dives deep into using the WebPack build system for both Angular and Express. This chapter discusses advanced optimization strategies to increase the loading speed and performance of our web applications.

Chapter 10, Debugging, explores the myriad of options available for debugging a MEAN stack web application. We'll cover the built-in debugger tools of Node.js as well as configuring IDE debuggers such as JetBrain's WebStorm. The chapter will also cover how to set up production error logging for Angular using the error logging service Sentry.io.

Chapter 11, Automated Testing, concludes the book with a review of the range of testing options within our MEAN stack web application. We'll cover writing unit and integration tests for our Express web application using Mocha and Chai. The reader will also be introduced to how to configure ESLint as a Node.js project linter, and use BrowserSync for cross-browser testing.

What you need for this book

To implement the recipes described in this book, you will need a desktop or laptop computer with at least 2 GB of available memory, running a Mac OS, Windows, or a Linux operating system of your choice. You'll need to have installed Node.js version 6 or greater with NPM version 4 or greater:

https://nodejs.org/en/download/

You will also need a text editor to follow along with the examples and recipe source code in this book. Also required is a modern browser with an integrated web developer toolkit such as Google Chrome, Mozilla Firefox, or Internet Explorer 11.

Who this book is for

If you are a JavaScript developer who wants to create high-performing, modern web applications with the MEAN stack, this is the book for you. Web developers familiar with some parts of the MEAN stack will find this a comprehensive guide to fleshing out the other technologies and skills they need to build all JavaScript web applications. Developers interested in transitioning from other web application stacks to an all-JavaScript environment will find a wealth of information about how to work in a MEAN stack environment.

To get the most from this book, you should have a general understanding of web servers and web applications. You are expected to have a basic understanding of running JavaScript, both in a web browser and outside it, using Node.js and the NPM package manager.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it…, How it works…, and There's more…). To give clear instructions on how to complete a recipe, we use these sections as follows:

Getting ready

This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There's more…

This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Start the web server by calling theservecommand.

A block of code is set as follows:

{ ... "project": { "name": "my-angular4-project" }, ... }

Any command-line input or output is written as follows:

ng get project.name

New terms and important words are shown in bold like this: However,Component, Directive, Pipe, Service, andGuardalso scaffold out additional useful files.

Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: We will see our post template rendering on the page with thepost works - 123text.

Warnings or important notes appear like this.
Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors .

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account. 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 at https://github.com/PacktPublishing/Mean-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file https://www.packtpub.com/sites/default/files/downloads/MEANCookbook_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Working with Angular 4

This chapter is an in-depth guide to configuring the front-end application of our MEAN stack web application using the Angular 4 JavaScript framework. We will explain how to upgrade from an existing Angular 2 application to Angular 4, as well cover how to generate components and routes using Angular-CLI.

In this chapter, we will cover the following recipes:

Upgrading from Angular 2 to Angular 4 using NPM

Generating a new Angular project using Angular-CLI

Configuring Angular-CLI project settings

Working with generators in Angular-CLI

Ejecting Angular-CLI from your project

Generating new routes in Angular-CLI

Defining a home page in your Angular routes

Handling 404 errors in an Angular project

Creating nested routes in Angular

Creating sibling routes in Angular

Programmatic page redirection in Angular

Route preloading with Angular modules

Running tests in Angular-CLI

Introduction

The revolution in JavaScript over the past 10 years has brought web applications leaps and bounds ahead of the preceding generation. These gains are perhaps most clearly visible through the use of JavaScript web application frameworks, such as Angular.

Angular is already considered to be the most popular and widely deployed web application framework to date. As a robust and fully featured framework, Angular provides a comprehensive approach to web application development that can be very appealing for developers looking a convention oriented JavaScript development environment. Angular’s reliability, modularity, and the ease with which it extends the web client experience are many of the reasons why developers choose Angular for the frontend layer of their web application stack.

The popularity of Angular is easy to find in large-scale developer community surveys, such as those provided by GitHub's most popular frontend JavaScript frameworks showcase and StackOverflow's 2017 developer survey results for top frameworks."Node.js and AngularJS continue to be the most commonly used technologies in this category."2017 Stack Overflow Developer Survey - Top Frameworks

You can visit the following links to learn more about about Angular's popularity compared to other frameworks:

https://github.com/showcases/front-end-javascript-frameworks

https://stackoverflow.com/insights/survey/2017/?utm_source=so-owned&utm_medium=blog&utm_campaign=dev-survey-2017&utm_content=blog-link#technology-frameworks-libraries-and-other-technologies

Upgrading to Angular 4 using NPM

For folks with existing Angular 2 applications, we will discuss the upgrade process to move from Angular 2 to Angular 4, which we will use for the rest of the recipes covered in this book. If you are starting from scratch with a new Angular 4 project, you may wish to skip this recipe and instead start with the Generating a new Angular project using Angular-CLI recipe. If you are interested in a comprehensive list of detailed changes that come with upgrading to Angular 4, please refer to the What's New in Angular 4Appendix in the back of this book.

Getting ready

Unlike some frameworks, there is no explicit upgrade command in Angular-CLI to move from Angular 2 to 4. Instead, the actual upgrading is done via updating the underlying NPM dependencies in our web application's package.json file. We can do this upgrade manually, but the simplest method is to use the NPM CLI to tell it exactly what packages we want it to install and save them to our project's package.json file.

How to do it...

Let’s take a look at the NPM commands for upgrading to Angular 4 in different environments:

On the Mac OSX and Linux environments, the following is the NPM command to upgrade to Angular 4:

npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@latest typescript@latest --save

On the Windows environment, the following is the NPM command to upgrade to Angular 4:

npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest typescript@latest --save

How it works...

The commands mentioned in the preceding section may seem very different, but in reality they both do exactly the same thing. Both install all the Angular 4's libraries to your node_modules directory and save the dependencies in your package.json file.

This installation command may take a few minutes to complete, but after it is done, your package.json file will be only file that's updated by this process:

An example of the package.json file showing difference before Angular 4 upgrade with NPM

The amazing thing about this upgrade process is that this is pretty much all there is to it. Upon restarting your Angular application, you should now have your legacy Angular 2 application running on Angular 4. If your application leveraged any of the deprecated or changed APIs mentioned in the What's New in Angular 4Appendix, you may see a compiler error at this time. You will need to review the change list and find the deprecation that is the closest match to the exception you are encountering and resolve that before trying again.

There’s more…

Working with dependencies in Angular can be tricky if you haven't had to manage a web application framework as robust as Angular before. Let's look at few of the most common types of dependency and package-related issues developers can get stuck on when upgrading their Angular applications.

Taking advantage of optional dependencies

One of the best parts about removing libraries, such as animations, from Angular 4's core dependencies is that we can now decide whether we want to or not. If our application doesn't need any animation capability, it is completely safe for us to not include it as a dependency in our package.json or as a part of our NPM install upgrade command. If we change our mind later, we can always install the animation library when the need arises. Depending on the functionality of your web application, you may also be able to do without the router, forms, or HTTP libraries.

Once your upgraded Angular 4 application successfully compiles, ensure that you take time to check that all your existing automated tests and the application functionality itself continue to function as expected. Assuming that your application is functioning properly, you will be enjoying an approximately 25% smaller generated file size as well as access to the new APIs and features.

Peer dependency warnings after upgrade

Angular 4 also depends on a number of other JavaScript libraries to function; some of those libraries are peerDependencies within Angular's own dependencies. That means that they must be fulfilled by your application in order for Angular to function. Some of these dependencies, such as TypeScript, were actually provided in the NPM install command; however, some of them, such as Zone.js, are not. These peerDependencies can vary even between minor version differences of Angular, so if you do see one of these warnings, your best bet is to manually update your package.json dependency for that library and try again:

An example of an unmet peer dependency warning during Angular 4 upgrade

Now that our Angular application is upgraded to Angular 4, we will move on to using Angular 4 for the rest of this book's Angular content. From now on, when I use the term Angular, it is specifically in reference to Angular 4. This conforms with Google’s own usage of the name, always using Angular generically to be the latest major SemVer version of the Angular framework.

Official Angular guidelines: Google has actually gone to great lengths to provide developers, bloggers, and the press with detailed examples of a proper usage of Angular terminology and the reasoning behind it. You can find more information about these guidelines on the official Angular blog, including a link to the official press kit: http://angularjs.blogspot.com/2017/01/branding-guidelines-for-angular-and.htmlhttps://angular.io/presskit.html.

Generating a new Angular project using Angular-CLI

For developers starting with Angular 4 from scratch, this section will cover how to use the Angular-CLI utility to generate a new project. There are many ways to create a new Angular project, but a very popular convention for getting started is to use a dedicated CLI utility. Angular-CLI is an all-in-one new project initializer and everything that we will need to run our new application locally. It includes a standalone web server, live reload server, and test runner to use in local development. We will use Angular-CLI in many of the examples throughout this book when working with Angular. There are also many useful features in Angular-CLI besides creating new projects, which we will discuss later in this chapter.

Getting ready

To create a new Angular project, we will use the Angular-CLI command-line utility. To install this utility, you must first have Node.js version 8.4.0 or greater installed locally as well as NPM version 4 or greater. You can check your local Node.js and NPM versions with the following commands:

node --version

npm --version

Using a node version mangement tool: Node.js version management can be an important aspect of maintaining consistent application builds, especially in a team environment. Angular-CLI doesn’t come with a predefined Node.js version management system, so adding a configuration file to your project for a Node.js version management utility, such as NVM, Nodenv, or Nodist, to your project early can help you solve configuration headaches down the road.

How to do it...

Let's look at the following steps to create an Angular project:

To install Angular-CLI, simply run the following command:

npm install -g @angular/cli

This may take several minutes to install Angular-CLI locally and make it ready and available to use in your project. Wait until the command prompt is ready, before proceeding to generate a new Angular project using Angular-CLI.

To create a new Angular application, simply type

ng new

,

followed by the name of your new application--in this case, I am using

my-angular-project

:

ng new my-angular-project

This will create a new project folder called

my-angular-project

and preinstall everything that we need to run our new Angular application locally.

How it works...

There are many options available when working with commands in Angular-CLI. For example, let's look at what other options are available for the new command:

ng new --help

This will show you all the available optional flags you can pass when initializing your project.

Whenever you are trying out a new command, passing the --help option can be a handy way to learn what options are available before running the command.

Now that we have our new Angular project set up, we can start the application locally using the built-in web server capability of Angular-CLI. Start the web server by calling the serve command:

ng serve

After running this command, you can actually see Angular compile all the default modules necessary to run your new application, including a message that tells you where to find your project in your local web browser:

** NG Live Development Server is running on http://localhost:4200 **

Tips for resolving port collision

Port collision is a problem that can happen when the port you are attempting to run your app on is already in use:

Port 4200 is already in use. Use '--port' to specify a different port.

This often happens if you accidentally leave open a previous instance of your application while trying to start another. On Unix systems, you can find and kill orphaned processes using the ps and grep commands:

ps aux | grep angular

This will return a process list you can consult to find your rogue Angular-CLI process:

nmcclay 88221 0.0 1.8 3398784 296516 ?? S 7:56PM 0:12.59 @angular/cli

Now that you have found your process, you can stop it with the kill command:

Kill 88221

Another common cause of this error can be running multiple different web applications locally. In this case, the best option is to simply change the default port used in the NPM start command of your package.json file:

start”: “ng serve --port 4500”,

Configuring Angular-CLI project settings

The .angular-cli.json file in the root of our project serves as a configuration file for our Angular-CLI application instance. We can customize theseconfigurations manually by editing the file itself, but we can also read and write from it using the Angular-CLI commandsgetandset.

How to do it...

Let's follow the steps below to learn how to read and write from our Angular application's configuration file using Angular-CLI:

To get the name of an Angular-CLI application, we would use:

ng get project.name

You can see how the

project.name

value

maps to the content of our

.angular-cli.json

file:

{ ... "project": { "name": "my-angular4-project" }, ... }

We can also write to this configuration file using the

set

command:

ng set project.name=my-awesome-angular-project

Note that any configuration changes here will not be picked up by live reload, and will require an entire restart of your Angular-CLI web server to be picked up by your application.

Working with generators in Angular-CLI

We can build many parts of our Angular application using the Angular-CLI utility. Components, views, routes, controllers, and services can all be generated in this manner. Scaffolding outnew functionalityusing a CLI helps us to save time when building our application by automatically creating the required boilerplate content and putting it exactly where we want it in our project.

We will use Angular-CLI as the preferred method for scaffolding out a new Angular functionality through the rest of the book.

How to do it...

Let's follow the steps below to create a new button component in our Angular application using Angular-CLI generate:

Angular-CLI's scaffolding command is

ng generate

, or the alias

ng g

. The

generate

command's function is to create stubs of ready-to-customize content for our application from blueprints within Angular-CLI.

ng g component my-button

After running generate, the command line will show an output of what content has been added to our project:

installing component

create src/app/my-button/my-button.component.css

create src/app/my-button/my-button.component.html

create src/app/my-button/my-button.component.spec.ts

create src/app/my-button/my-button.component.ts

update src/app/app.module.ts

How it works...

If we look at our project, we can see that Angular-CLI has automatically scaffolded out a my-button directory that contains stubs for all of the files that make up our button component. This includes its class boilerplate, my-button.component.ts, its template,my-button.component.html, its style sheet,my-button.component.ts, and its test file,my-button.component.spec.ts:

These stub files are very generic, but they cover virtually all the boilerplate code involved in creating a new component in Angular. Another detail handled for us is the actual importing of the component into our application through app.module.ts:

...

import { MyButtonComponent } from './my-button/my-button.component';

@NgModule({...

declarations

: [ AppComponent

,

MyButtonComponent

]

,

...})

export class

AppModule { }

The module declarations section here has automatically been updated for us by the generate command, so all that we need to do is invoke the component within a template of our application:

<app-my-button></app-my-button>

If we look back at our application, wewillsee the wordsmy-button worksprinted out from wherever in our app we have invoked the component.

Generating content into specific locations: Angular-CLI's generate command can accept a file path along with a name in order to control where your content will be generated. For instance, if I had an admin module in my Angular application where I organized all the functionalities that are unique to my administrator user experience, I might want to nest an admin unique component there with ng g component admin/dashboard. This will create all my component files in a directory under src/app/admin/dashboard instead of in my root module space.

We can create many types of content using the generate command. The syntax for scaffolding out a new piece of content is always the same, as follows:

ng generate <blueprint> <name>

You can find a complete list of all the available blueprints and examples of their usage in the following table:

Blueprint

Angular-CLI

Component

ng generate component my-new-component

Directive

ng generate directive my-new-directive

Pipe

ng generate pipe my-new-pipe

Service

ng generate service my-new-service

Class

ng generate class my-new-class

Guard

ng generate guard my-new-guard

Interface

ng generate interface my-new-interface

Enum

ng generate enum my-new-enum

Module

ng generate module my-module

Many of these generated blueprint types create simple boilerplate files in the root of our app module directory. However, Component, Directive, Pipe, Service, and Guard also scaffold out additional useful files.

Angular-CLI add-ons: The future of Angular-CLI and its convention-oriented approach to Angular development is evolving very rapidly. One feature on the future roadmap for Angular-CLI that will greatly shape the usage of it by the community is add-ons. Add-ons will allow developers to plug in functionality to Angular-CLI through shared modules to enhance their Angular applications. For example, custom blueprints for Angular-CLI could be created through an add-on, and allow developers to scaffold out custom content using the generate command.

There's more...

There are many types of content you can scaffold out with Angular-CLI's generators. Let's take a look at how we can generate new services in our Angular application using Angular-CLI's generate command.

Generating new services with Angular-CLI is very similar to generating components, but with the following few key differences:

ng g service my-store

installing service

create src/app/my-store.service.spec.ts

create src/app/my-store.service.ts

WARNING Service is generated but not provided, it must be provided to be used

Scaffolding a new service generates fewer files than a component and also nests the service at the root of our application directory by default instead of nesting it in its own namespace. The warning that is presented after creating our service stub files notifies us that, unlike components, services have to be manually provided to our application. Unlike components that are naturally isolated from each other, services can have explicit dependencies and load order requirements that Angular-CLI is unable to predict. In general, adding these services to your application is easily done by importing and adding the service to the provider list:

...

import { MyStoreService } from './my-store.service';

@NgModule({ ... providers: [ MyStoreService ] ...})

export class

AppModule { }

With the service provided to your application, it is now available for use.

Generating guards: Guards generated with Angular-CLI also show the warning that they are not provided by default. Adding a generated guard to your application is identical to adding a service.

Ejecting Angular-CLI from your project

While the convention-oriented approach of Angular-CLI can be a positive thing for many developers, sometimes, you may find the need to manually take back control of your build process and project configuration. Luckily, there is an easy way to convert an Angular-CLI project to a generic project using the eject command.

Getting ready

Let's take back control of our Angular application's build process from Angular-CLI. We may need this to do a variety of tasks, including customizing WebPack builds or just getting more granular control of our local web server runs. Ironically, we will use Angular-CLI to remove our application from Angular-CLI's control.

How to do it...

Perform the following steps to remove Angular-CLI from your project:

First, you must remove your

start

script from your

package.json

file, as it will be overwritten in this process.

Then, run the

ng eject

command:

How it works...

Your project has been fully converted over to a standard Angular project, with a fully defined build toolchain ready in a new webpack.config.js file. Note that this conversion is a one-way process, and should only be done if you are ready to take full control of your application's build process.

The build process that remains is actually a standard WebPack based build. We will discuss WebPack builds and how to customize them for your application more in Chapter 9, Build Systems and Optimizations.

Generating new routes in Angular-CLI

Now we are ready to start really digging into the details of routing in Angular; how to create new routes and how to redirect to routes in your application, including error handling. We'll also cover how to nest routes and use route preloading to speed up your application navigation.

Creating new routes: Routing in Angular is handled by the optional Angular router package and must be imported into your application to be used.

Getting ready

To mount the router to the root of our application, we must first import the RouterModule from the router and call the forRoot method to tell the router that we are setting up routes on the root of our web application:

import { NgModule } from '@angular/core';import { FormsModule } from '@angular/forms';import { HttpModule } from '@angular/http';

import { RouterModule } from '@angular/router'

;

import

{

AppComponent

}

from

'

./app.component

'

@NgModule({ ... imports: [ BrowserModule

,

FormsModule

,

HttpModule

,

RouterModule.forRoot([])

]

,

...})

export class

AppModule { }

With the router set up on the root of our web application, we are now able to provide a mapping between the Universal Resource Indentifier (URI) of the route that we want to show in the browser and the component we want to be rendered on that route. For the sake of simplicity, we will imagine we are building a simple blog website and will stub out two components: posts and authors. Posts will show all the available blog posts on our blog, whereas authors will show a list of all authors of blog posts on our blog:

ng g component posts

ng g component authors

This will scaffold out the two components as well as add them to our app module so that we can start routing to them.

How to do it...

After scaffolding the two components and adding them to our app module, let’s follow these steps to add our routes:

First, we will need to create the route map between these components and the two routes we want to create:

/posts

and

/authors

.

We will do this by passing an array of route configuration objects into the

forRoot

method of our

RouterModule

. This configuration tells the router that the

/posts

route will resolve with the

PostsComponent

, and the

/authors

route will resolve with the

AuthorsComponent

:

@NgModule({ ... imports: [ ... RouterModule.forRoot(

[

{

path: "posts", component: PostsComponent

}, {

path: "authors", component: AuthorsComponent

}

]

) ], ...})export class AppModule { }

With our routes and components now properly associated, we just need to provide an outlet, where this content can be presented, and links to make navigating to it more easily. We can add both of these to our

app.component.html

template, as follows:

<nav>

<a routerLink="/posts">Posts</a>

<a routerLink="/authors">Authors</a>

</nav>

<router-outlet></router-outlet>

How its works...

Instead of a traditional href attribute, we tell the router to navigate to a route we've configured by attaching the routerLink directive to it. This directive takes a path string that matches a path configured with our router. Next, we provide the outlet where our content will be presented through when a route is active with the router-outlet directive. With these two elements in place, we can see two folders called Posts and Authors in our app folder; clicking on either link will add the posts works!text for /posts and authors works! for /authors.

By updating the template within our components, we can change the content that shows up when the user navigates to the associated route. We can also change the template in app.component.html to alter the shared master template that is used by both routes. We will explore this topic more in the next chapter when we upgrade our application's styling.

Defining a home page in your Angular routes

Often, we will want our web application to have a specific home page for our application. We will simply define a home page route in our Angular route configuration.

How to do it...

We can define a home page with our RouterModule configuration that will be served when the user loads the top level of our application, as follows:

First, we will generate a new component for controlling our home page. We will create this component using the Angular-CLI

generate

command:

ng generate component home

Next, we'll simply add our

HomeComponent

to our

/src/app/app.module.ts

route configuration:

...

import { HomeComponent } from './home/home.component';

@NgModule({ declarations: [ AppComponent, AuthorsComponent, PageNotFoundComponent, AuthorComponent,

HomeComponent

], imports: [ BrowserModule, BrowserAnimationsModule, FormsModule, HttpModule, RouterModule.forRoot(

{

path: "",

component: HomeComponent

}

,{ path: "posts", component: PostsComponent },{ path: "authors", component: AuthorsComponent }), PostsModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }

Now when we visit

http://localhost:4200