TypeScript 2.x for Angular Developers - Christian Nwamba - E-Book

TypeScript 2.x for Angular Developers E-Book

Christian Nwamba

0,0
41,99 €

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

Mehr erfahren.
Beschreibung

Write better, reusable, and predictable Angular apps with typed logic

About This Book

  • Leverage the power of TypeScript for developing large-scale Angular apps
  • Take advantage of the cutting-edge features of TypeScript 2.x to build high-performing, maintainable applications
  • Explore the TypeScript implementation of modules, classes, and annotations with Angular components

Who This Book Is For

This book is for developers who would like to learn to use TypeScript to develop Angular applications. A basic JavaScript knowledge would be beneficial.

What You Will Learn

  • Move from loose types to predictable strict types
  • Write self-documented API methods and data structures
  • Understand custom generic types for complex data structures
  • Implement Contract with Interfaces
  • Enhance Dependency Injection in Angular via class constructors
  • Explore TypeScript advanced types
  • Build Interactive web apps with Angular and TypeScript

In Detail

TypeScript, a superset of JavaScript, is the default language for building Angular applications from Google. TypeScript 2.0 adds optional static types, classes, and modules to JavaScript, to enable great tooling and better structuring of large JavaScript applications.

This book will teach you how to leverage the exciting features of TypeScript while working on Angular projects to build scalable, data-intensive web applications. You will begin by setting up and installing TypeScript and then compile it with JavaScript. You will then learn to write simple JavaScript expressions with TypeScript. You will then go through some built in TypeScript types and accessors. Further you will build web components using TypeScript Interfaces and Decorators. You will go through the Angular form module, which will enable you to write predictable typed forms with TypeScript and learn to use typed DOM events. You will also build a single-page application using the Router module. Lastly, you will consume API data with Angular's HTTP Module and handle responses with RxJS observables. At the end of the book, you will go through different testing and debugging techniques.

Style and approach

A step-by-step, tutorial-based guide

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 178

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.



TypeScript 2.x for Angular Developers

 

 

 

 

 

 

 

 

 

 

Harness the capabilities of TypeScript to build cutting-edge web apps with Angular

 

 

 

 

 

 

 

 

 

 

Christian Nwamba

 

 

 

 

BIRMINGHAM - MUMBAI

TypeScript 2.x for Angular Developers

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(s), 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 endeavoured 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: December 2017

 

Production reference: 1051217

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

ISBN: 978-1-78646-055-4

 

www.packtpub.com

Credits

AuthorsChristian Nwamba

 

Copy EditorMuktikant Garimella

 

ReviewersAndrew Macrae

 

Project CoordinatorUlhas Kambali

 

Commissioning EditorMerint Mathew

 

ProofreaderSafis Editing

 

Acquisition EditorReshma Raman

 

IndexerFrancy Puthiry

 

Content Development EditorNikhil Borkar

 

GraphicsJason Monteiro

 

Technical EditorJash Bavishi

 

Production CoordinatorShantanu Zagade

 

About the Author

Christian Nwamba is a Lagos, Nigeria-based full stack engineer, developer, and evangelist. He spends most of his life building user experiences with JavaScript and spreading the word to other developers through conferences, meetups, and technical articles.

He has worked with quite a few interesting SaaS companies, such as Cloudinary, Pusher, and Auth0, and has published articles on popular blogs, such as Sitepoint, Scotch.io, Codementor, and Web Designer Depot. This is his first book and he's very proud of the effort he put in to make it enjoyable for the readers.

He has a lot of interest in community building and efforts, especially in Africa. He does this by organizing and facilitating meetups/conferences (forLoop Africa, Angular Nigiera, GDGs, and more).

Acknowledgments

Before anything, I would like to express my sincere gratitude to my parents, Edwin Nwamba and Helen Nwamba, for nurturing and playing a huge role in my literary and technical upbringing. Their guidance gave me a great head start, which made all this possible.

Besides my parents, I would also like to thank the Scotch, Cloudinary, and Packt teams for the continuous and unrestrained support they showed to me during my time writing this book. I couldn’t have asked for a better support in all sincerity.

My sincere thanks also go to Chris Sevilleja, Nick Cerminara, and Prosper Otemuyiwa for challenging me to become even better at what I do and for their encouragement, insightful comments, and hard questions. Also, I thank Marcel Nwamadi and Olayinka Omole for contributing to the technical success of this work.

I would like to thank Angular Nigeria and ForLoop Africa, two communities whose growth in recent times spurred me to carry on and not to relent in my efforts to make programming the mainstay in Africa.

I thank my friends, William Imoh, Raphael Ugwu, Nnaemeka Ogbonnaya, and Chioma Imoh, for the stimulating discussions, the constant reminders and evaluations, and for being with me in good times and bad through the last five years.

Last but not least, I would like to thank my siblings, Kelechi Nwamba, Ezinne Nwamba, Ekoma Nwamba, and Chioma Nwamba, for supporting me throughout my life.

About the Reviewer

Andrew Leith Macrae first cut his programming teeth on an Apple IIe, poking bytes into the RAM. Over the years, he has developed interactive applications with Hypercard, Director, Flash, and more recently, Adobe AIR for mobile. He has also worked with HTML since there was HTML to work with and is currently working as a senior frontend developer at The Learning Channel (www.tsc.ca), using Angular 4 with TypeScript. He is convinced that TypeScript is the future of JavaScript, bringing the structure and discipline of strongly typed object-oriented language to facilitate efficient, intentional coding for the development of large-scale applications for the web.

You can find out more about Andrew or contact him at www.adventmedia.net.

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/1787286436.

If you'd like to join our team of regular reviewers, you can email 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

Conventions

Reader feedback

Customer support

Downloading the example code

Downloading the color images of this book

Errata

Piracy

Questions

From Loose Types to Strict Types

Term definitions

Implications of loose types

The problem

Mitigating loose-type problems

The typeof operator

The toString method

Final Note

Summary

Getting Started with TypeScript

Setting up TypeScript

Hello World

Type annotation in TypeScript

ES6 and beyond

User story

Final notes

Summary

Typescript Native Types and Features

Basic types

Strings

Numbers

Boolean

Arrays

Void

Any

Tuple

Enums

Functions and function types

Function parameters

Function return value

Optional parameters

Interfaces

Interfaces for JavaScript object types

Optional properties

Read-only properties

Interfaces as contracts

Decorators

Decorating methods

Decorating classes

Decorator factories

Summary

Up and Running with Angular and TypeScript

Setting up Angular and TypeScript

Creating a new Angular project

Project structure

Generating files

Basics concepts

Components

Templates

Component styles

Modules

Unit testing

Summary

Advanced Custom Components with TypeScript

Lifecycle hooks

DOM manipulation

ElementRef

Hooking into content initialization

Handling DOM events

View encapsulation

Emulated

Native

None

Summary

Component Composition with TypeScript

Component composability

Hierarchical composition

Component communication

Parent-child flow

Intercepting property changes

Child–parent flow

Accessing properties and methods of a child via a parent component

Accessing child members with ViewChild

Summary

Separating Concerns with Typed Services

Dependency injection

Data in components

Data class services

Component interaction with services

Services as utilities

Summary

Better Forms and Event Handling with TypeScript

Creating types for forms

The form module

Two-way binding

More form fields

Validating the form and form fields

Submitting forms

Handling events

Mouse events

Keyboard events

Summary

Writing Modules, Directives, and Pipes with TypeScript

Directives

Attribute directives

Handling events in directives

Dynamic attribute directives

Structural directives

Why the difference?

The deal with asterisks

Creating structural directives

Pipes

Creating pipes

Passing arguments to pipes

Modules

Summary

Client-Side Routing for SPA

RouterModule

Router directives

Master-details view with routes

Data source

Blog service

Creating routes

Listing posts in the home component

Reading an article with the post component

Summary

Working with Real Hosted Data

Observables

The HTTP module

Building a simple todo demo app

Project setup

Building the API

Installing diskdb

Updating API endpoints

Creating an Angular component

Creating application routes

Creating a todos service

Connecting the service with our todos component

Implementing the view

Build a user directory with Angular

Create a new Angular app

Create a Node server

Install diskDB

Create a new component

Create a service

Updating user.component.ts

Updating user.component.html

Running the app

Summary

Testing and Debugging

Angular 2 testing tools

Jasmine

Main concepts of Jasmine

Karma

Protractor

Angular testing platform

Using Karma (with Jasmine)

Creating a new project

Installing the Karma CLI

Configuring Karma

Testing the components

Testing services

Testing using HTTP

Testing using MockBackend

Testing a directive

Testing a pipe

Debugging

Augury

Augury features

Component tree

Router tree

Source map

Summary

Preface

Deciding to learn Angular can be quite overwhelming. This is because the de facto way of writing an Angular app is by using a superset language, TypeScript, which is fairly new. Ironically, TypeScript simplifies how Angular apps are written by providing strict types (as seen in strictly typed languages such as Java), which improves the predictive behavior of the apps we write. This book is intended to assist you as a beginner/intermediate Angular developer with little or no knowledge of TypeScript or strict typing, in general, by explaining the core concepts of TypeScript.

What this book covers

Chapter 1, From Loose Types to Strict Types, discusses the problems developers faced before TypeScript was introduced, and what problems TypeScript solves. We will do this by discussing loose types and their challenges, and show some examples of how these challenges were being tackled previously and why TypeScript is a better choice.

Chapter 2, Getting Started with Typescript, gives a summary of TypeScript's core concepts with practical examples on how to set up a vanilla JavaScript plus TypeScript project. All loosely typed examples in Chapter 1, From Loose Types to Strict Types, will be rewritten with TypeScript to demonstrate TypeScript's efficiency.

Chapter 3, Typescript Native Types and Features, takes a deep dive into built-in TypeScript strict types that match existing JavaScript loose types. Each type will be discussed extensively with working examples, showing how it should be used and how it should work.

Chapter 4, Up and Running with Angular and TypeScript, discusses how TypeScript applies to Angular. To do so, Angular needs to be up and running with the help of the CLI tool. In this chapter, we will discuss what it takes to have Angular and TypeScript work together. We will also cover the basic Angular concepts that you could find in a Hello World example.

Chapter 5, Advanced Custom Components with TypeScript, discusses the concept of web components and how Angular builds on web components with TypeScript. We will see how to create components with classes, implement lifecycle hooks with TypeScript interfaces, and define components, metadetails using TypeScript decorators.

Chapter 6, Component Composition with TypeScript, discusses how Angular is component-based. It explains that components are composed together as building blocks to make a fully functional app. We will discuss modularizing components using composition with examples and component interaction (data transfer and events). In doing so, we will see how TypeScript is used to keep us in check with all these moving parts.

Chapter 7, Separating Concerns with Typed Services, discusses how it’s bad practice to allow our logic to live in our components. In such a case, Angular allows you to provide API methods via services that these components can consume. We will discuss how TypeScript helps us create contracts (using types) between these API methods and the components.

Chapter 8, Better Forms and Event Handling with TypeScript, explains how the Angular form module enables us to write predictable typed forms with TypeScript, which is a perfect means of collecting data from our app users. We will also see how to use typed DOM events (for example, click, mouseover, and keydown) to respond to user interactions.

Chapter 9, Writing Modules, Directives, and Pipes with TypeScript, discusses the secondary building blocks of Angular and how they are best used with TypeScript. You will learn how to build custom directives and pipes in Angular with types and decorators.

Chapter 10, Client-Side Routing for SPA, explains Single Page Applications (SPAs), which are built by handing over routing to the client with JavaScript rather than the server. We will discuss how, with Angular and TypeScript, we can use the router module to build multiple view apps with just a single server route.

Chapter 11, Working with Real Hosted Data, takes a deep dive into consuming API data with Angular’s HTTP module. You will learn how to make an HTTP request right from our Angular app. Data fetched from this request can then be rendered by components.

Chapter 12, Testing and Debugging, covers recommended practices on unit testing Angular building blocks. These include components, services, routes, and more.

What you need for this book

The examples covered in this book can be implemented on a Windows, Linux, or macOS PC. You'll need to install Node and npm to work with TypeScript, and a decent web browser.

Who this book is for

This book is intended to assist a beginner/intermediate Angular developer with little or no knowledge about TypeScript or strict typing, in general, by explaining the core concepts of TypeScript. It’s also a perfect book for developers who have already worked with Angular 1.x or other frameworks and are trying to move to Angular 2.x.

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: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

[default]exten => s,1,Dial(Zap/1|30)exten => s,2,Voicemail(u100)exten => s,102,Voicemail(b100)exten => i,1,Voicemail(s0)

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

[default]exten => s,1,Dial(Zap/1|30)exten => s,2,Voicemail(u100)

exten => s,102,Voicemail(b100)

exten => i,1,Voicemail(s0)

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

# cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample

/etc/asterisk/cdr_mysql.conf

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen."

Warnings or important notes appear in a box 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 emailed directly to you. You can download the code files by following these steps:

Log in or register to our website using your email 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

.

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/TypeScript-2.x-for-Angular-Developers. 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 from https://www.packtpub.com/sites/default/files/downloads/TypeScript2.xforAngularDevelopers_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.

From Loose Types to Strict Types

JavaScript is loosely typed. It's worth repeating, JavaScript is loosely typed. Notice how the sentence is passive--we cannot categorically hold someone responsible for the loose-type nature of JavaScript just as we can't do so for other famous glitches of JavaScript.

A detailed discussion on what loose-types and loosely typed languages are will help aid your understanding of the problem that we plan to solve with this book.

When a programming language is loosely typed, it means that the data passed around using variables, functions, or whatever member applicable to the language does not have a defined type. A variable x could be declared, but the kind of data it holds is never certain. Loosely typed languages are contrary to strongly typed languages, which enforce that every declared member must strictly define what sort of data it can hold.

These types are categorized into:

Strings

Numbers (int, float, and so on.)

Data structures (arrays, lists, objects, maps, and so on.)

Boolean (true and false)

JavaScript, PHP, Perl, Ruby, and so on, are all examples of loosely typed languages. Java, C, C#, are examples of strongly typed languages.

In loosely typed languages, a member may be initially defined as a string. Down the line, this member could end up storing a number, a boolean, or even a data structure. This instability leads us to the implications of loosely typed languages.