Yakov Fain's Blog

My notes about everything in IT

A Toolbox of the Angular 2 Developer

with 10 comments

Say you need to hire a Web developer experienced with Angular. What would you expect the developer to know? Well, he or she needs to know how to create Angular components, what’s data binding, dependency injection, routing et al. But this is just the tip of the iceberg. Below is a list of languages and tools that professional Angular developers use.

* JavaScript is a de-facto standard programming language for the front-end of Web applications. ECMAScript 6 (ES6) is the latest standardized specification for scripting languages and JavaScript is the most popular implementation of this spec.

* TypesScript is a superset of JavaScript that makes developers more productive. TypeScript 1.5 (currently in Beta) supports most of the features of ES6 and adds optional types, interfaces, meta-data annotations and more. The Angular 2 framework itself is written in TypeScript.

* DefinitelyTyped is a vast collections of files describing the API of 500+ libraries and frameworks. Using DefinitelyTyped allows the TypeScript compiler and IDEs know the types expected by the APIs of these libraries.

* Angular 2. It’s a complete re-write of a popular Angular 1.x. It’s currently in Alpha.

* Transpilers. Since most of the Web browsers support only the ECMAScript 5 syntax, you need to transpile (convert, compile one source code to another) the code written in TypeScript or ES6 to its ES5 version for deployment. Angular developers use Babel, Traceur, and the TypeScript compiler.

* Node.js is a platform built on Chrome’s JavaScript engine. Node includes both a framework and a runtime environment to run JavaScript code outside of the browser. We don’t use the framework, but you can’t avoid using the Node runtime to install required tools for developing Angular applications.

* npm is a package manager that allows to download tools and reusable JavaScript modules. Npm has a repository of thousands modules, but we’ll mostly use it for installing developer’s tools, e.g. the TypeScript compiler, the task runner Gulp and more.

* Bower is also a package manager but for application dependencies. Your application will need the Angular framework. Install it with Bower. Need a unit testing framework Jasmine? Install it with Bower.You can install literally any
JavaScript library or a framework with Bower.

* SystemJS is a universal module loader, which load modules created in ES6, AMD or CommonJS standards.

* jspm is yet another package manager. Why do we need another package manager if npm and bower can take care of all dependencies? Modern Web applications consist of loadable modules and jspm integrates SystemJS, which makes loading modules a breeze.

* Grunt is a task runner. Lots of steps need to be performed between developing and deploying the code. All these steps must be automated. You may need to transpile the code written in TypeScript or ES6 into widely supported ES5 syntax. The code, images, and CSS files need to be minimized. You may want to include the tasks that will check the code quality and unit-test your application. With Grunt you configure all the tasks and their dependencies in a JSON file so the process is 100% automated.

* Gulp is a newer than Grunt task runner. It can automate all the tasks just as Grunt does, but instead of configuring the process in JSON you simply program it in JavaScript. This allows you to debug it if need be.

* jslint and eslint are code analyzers that looks for problematic patterns in a JavaScript program or JSON-formatted documents. These are code quality tools. Running a JavaScript program trough jslint or eslint results in a number of warning messages suggesting how to improve the code quality of this program.

* tslint is is a code quality tool for TypeScript. It has an collection of rules (can be extended) to enforce the recommended coding style and patterns.

* Minifiers make files smaller. For example, in JavaScript they remove comments, line breaks, and make variable names shorter. Minification can also be applied to HTML, CSS, and image files.

* Bundlers combine multiple files and their dependencies in a single file.

* Testing frameworks. Since JavaScript syntax is very forgiving, the application code requires testing. We use the Jasmine framework and the test runner called Karma.

* IDE. Both JavaScript and TypeScript are well supported by modern IDEs and text editors such as WebStorm, Visual Studio, Visual Studio Code, Sublime Text, Atom et al.

* Browser as a development environment. All major Web browser comes with developer tools that allow to debug your programs right inside the browser. We use Chrome Developer Tools.

* Web Components. This is the future of Web development. The goal is to develop reusable widgets for the Web application. We already started using the Polymer library of Web components in a pilot project and like it a lot.

This list may look intimidating, but it can be mastered one step at a time. Programming in Angular 2 is easier than in Angular 1.x, but the initial environment setup should be done right so you can really enjoy the development process.

Written by Yakov Fain

July 4, 2015 at 11:47 am

Posted in Angular2, javascript

The private in TypeScript is kinda private

with 6 comments

TypeScript includes the keywords public, protected, and private to control access to the members of a class such as properties or methods. Public class members are visible from within and outside the class, protected are visible form the class and its descendents, and private are visible from within the class only. But being a superset of JavaScript, which doesn’t support the private keyword, using private members in TypeScript is not what you may expect.

Let’s look at the example of the class Person, which has three public and one private property.

class Person {
    public firstName: string;
    public lastName: string;
    public age: number;
    private ssn: string;

    constructor(firstName:string, lastName: string, age: number, ssn: string) {
        this.firstName = firstName;
        this.age = age;
        this.ssn = ssn;

var p = new Person("John", "Smith", 29, "123-90-4567");

console.log("Last name: " + p.lastName + " SSN: " + p.ssn);

The TypeScript compiler properly reports an error at the last line where I tried to access the private variable ssn. Here’s the error:

“Error:(17, 53) TS2341: Property ‘ssn’ is private and only accessible within class ‘Person’.”

But this should have been marked as a warning, because the TypeScript compiler generates the JavaScript code anyway, which looks like this:

var Person = (function () {
    function Person(firstName, lastName, age, ssn) {
        this.firstName = firstName;
        this.age = age;
        this.ssn = ssn;
    return Person;

var p = new Person("John", "Smith", 29, "123-90-4567");
console.log("Last name: " + p.lastName + " SSN: " + p.ssn);

To see the code generation in action, visit the TypeScript Playground at http://bit.ly/1GKUeV0. As you see all traces of privacy have been removed, the property ssn has been exposed to the outside world as every other Property on the Person object. There must be some reason why creators of the TypeScript compiler didn’t turn the class Person into the JavaScript closure that would actually make ssn private, for example:

var Person = (function () {
    var _ssn;
    function Person(firstName, lastName, age, ssn) {
        this.firstName = firstName;
        this.age = age;
        _ssn = ssn;
    return Person;

But it is what it is. So when you use the private keyword in TypeScript, keep in mind that it just suggests you to be nice and not access it directly, but write public getter and setter methods instead.

Let’s extend the class Person like this:

class Employee extends Person{
    ssn: number;

TypeScript’s compiler will give you an error:

Error:(17, 53) TS2341: Property ‘ssn’ is private and only accessible within class ‘Person’.

But it’ll still generate the JavaScript code unless you add a compiler option –noEmitOnError to not generate JavaScript until all TypeScript syntax errors are fixed. Also, to ensure that the directory with generated JavaScript files doesn’t have files from previous compilation use the build automation tool like Gulp or Grunt with a clean task to remove old generated files on each compile.

Having said that, I still like TypeScript. Developing in TypeScript is clearly more productive than in JavaScript.

P.S. IMO, protected variables are useless in any object–oriented language.

Written by Yakov Fain

June 30, 2015 at 10:41 pm

Posted in javascript, TypeScript

Writing Technical Books 101

with 4 comments

So you’re an expert programmer and decided to write a technical book? Think twice. Why do you want to write it? These are possible answers:

1. All these years I’ve been using the IT knowledge so generously shared by other people, and it’s time to give back to the community. Great answer! But does it have to be a book? Have you tried answering other people’s questions on StackOverflow? Have you’ve written a couple of dozen of blogs that people read and like? If the answer is no to any of these questions, start there because writing a book is harder.

2. I want to become a published author. This will give me better recognition in the industry and will look good on my resume. I hear you. This is true unless the book you’ll write will suck. If your book will get mostly negative reviews, you’ll remove it from your resume. But you can’t remove it from the Internet, can you?

3. I want to earn some extra cash in the form of royalties. This is the worst possible reason for writing a technical book, because the money is not there. This is not to say that there are no people making a good living just by writing technical books, but the chances that you’ll become one of them are similar to a fiction book writer becoming the next J.K. Rolling.

I’ll give you some of my numbers. My most financially successful technical book so far is the first edition of Java 24-Hour trainer, which brought me $40K in royalties over four years. Apparently the publisher considered this book a financial success as well, because they offered me to write a second edition of this book. So consider making $10K a year in royalties a good result for your book.

Still want to write your book? Now let me ask you some questions.

1. Do you have a discipline to write every day to meet the schedule? You may be surprised, but the publisher will request your manuscripts to be submitted by the certain dates. The editors will be contacting you asking about the status of your chapters, because they also have their deadlines to meet.

The most common mistake the rookie writers can make is not writing daily. You can’t just live your regular life and write something once in a while. You need to think about your book all the time. Missing a day of writing is a slippery slope, which will require more time and discipline to continue where you left off.

2. Are you ready to listening to valid complaints of your spouse/girlfried/boyfriend that you’re stealing the time from your family, kids, and other fun things you could have done together? And they are right. You are going to be stealing their time.

3. Are you ready to seeing your book illegally distributed for free on all these torrent repos as soon as it hits the book stores? How come? After all this dedication and time spent to make the world a better place they what your content for free? Yes they do. Have you ever downloaded a movie or a song for free without paying for it? You are the same as all these people downloading your book for free. No complains here, but try to turn negative into positive. These free downloads make your name recognizable in the industry, which may be a good thing when negotiating salary or offering training classes.

4. Are you ready to be called an idiot for a typo in the code samples? Actually, I need to give a compliment to my American readers here. They are more polite than the rest of the world , and in most cases will try to give you a constructive criticism.

Still want to write after reading all this? I’m really happy for you! Because I also continue writing despite all these cons. After every completed book project I say to myself, “Never again”, and then start working on a new book.

To summarize, these are some rules I can share with you based on my book writing experience.

1. Never try to make the draft of your chapter perfect before submitting it to the publisher. They’ll modify the text anyway unless you have a college degree in writing, which most software developers don’t. Push the chapter our of the door quickly. Fail fast! Get the feedback as soon as possible to have more time for fixing it.

2. Write every day. Even if it’s just one or two paragraphs. The process has to be continuous. Even the writer-alchoholic Henry Chinaski forced himself to write every day. So booze, gym, or other time-consuming hobbies are not excuses for not writing daily.

3. Don’t write in MS Word or a similar word processor. Use any plain text editor and the Asciidoc markup language with future generation of the code in HTML/PDF/EPUB/MOBI formats. I’m writing my third book with Asciidoc and am pretty happy with it.

4. Store all your drafts on GitHub even if you’re the only author of your book. GitHub also has a very nice feature called GitHib Pages that allows to publish your drafts online. For example, this is how my free book Java For Kids looks at GitHub pages. If you don’t want to make your drafts publicly available, either buy a private repository on GitHub
or create it for free on BitBucket.

P.S. Most likely, you’ll find grammar errors in the text of this blog. It’s OK. I need to push it out the door ASAP to get your feedback sooner. Please leave comments and I’ll fix the mistakes later.

P.S.S. I’ve stolen the time allocated for writing a chapter for my next book on Angular 2 and wrote this blog instead. Stupid me.

Written by Yakov Fain

June 27, 2015 at 3:40 pm

Posted in IT Career

ECMAScript 6 modules in the browser with Traceur

leave a comment »

ECMAScript 6 standardizes the syntax of modules. A module is simply a Javascript file that you can load either on the application startup or lazily on the as-needed basis. ES6 modules give you complete control on what code to export to the external scripts and what to keep private to the module. Prepend a variable, a function, or a class definition with the keyword export, and all other scripts in your project can import the module’s API using the import keyword. For details of using modules, read this great post by Dr. Axel Rauschmayer.

But the ECMAScript 6 specification doesn’t define module loaders, which can be used both in the browsers and in the standalone JavaScript engines. Eventually all Web browsers will support the System object that knows how to import modules, but meanwhile you can use the polyfill ES6 Module Loader or, if you want to go fancy and ensure that your AMD and/or CommonJS modules are also loaded in a standardized fashion, go with the universal system module loader called SystemJS.

Since ES6 syntax is not fully supported by any of the modern browsers, you’d need to transpile the code from ES6 to ES5 using one of the transpilers such as Traceur or Babel. In this blog I’ll show you how to dynamically load ES6 modules in the Web browsers with auto-transpiling using Traceur. To run this example on your computer you’ll need to have node.js with npm installed.

First, you need to download and install es6-module loader in any directory by running the following npm command:

npm install es6-module-loader

Then create an application folder and copy the file es6-module-loader.js there (this is a minimized version of the loader that was downloaded by npm). Our sample application will have two additional files: moduleLoader.html and shipping.js. For simplicity I’ll keep all these files in the same folder.

Imagine that we develop an online store with a large code base. To avoid creating a monolithic application, we’ve split it into loadable modules. In particular, the module that handles shipping should be loaded only if the user clicks the Shipping button. Here’s the code of our “huge” shipping module:

export function ship() {
    console.log("Shipping products...");

function calculateShippingCost(){
    console.log("Calculating shipping cost");

Since I used the export keyword only in front of the ship() function, the function calculateShipptingCost() will remain private for the module and won’t be accessible from the outside. No need to implement the module design pattern with immediately-invoked function expressions, and no need to use a third-party framework like RequireJS.

The file moduleLoader.html includes a script that loads and uses the shipping module. In this example I use Traceur for the on-the-fly transpiling of the ES6 code to ES5 so it can run in any browser. Here’s the file moduleLoader.html:

<!DOCTYPE html>
    <script src="https://google.github.io/traceur-compiler/bin/traceur.js"></script>
    <script src="es6-module-loader.js"></script>

  <button id="shippingBtn">Load the Shipping Module</button>

<script type="module">

let btn = document.querySelector('#shippingBtn');
btn.addEventListener('click', () =>{

         .then(function(module) {
             console.log("Shipping module Loaded ", module);


             module.calculateShippingCost();  // will throw an error
             console.log("In error handler", err);



In Line 5 we load the Traceur for transpiling. In line 6 we load es6-module-loader to support the System object that will load the shipping module using the import() call when the user clicks on the button. The import returns the ES6 Promise object, and when the module is loaded, the function specified in then() will be executed. In case of an error the control goes to the function catch().

Inside the then() we print the message on the console and invoke the exported function ship(). After that we try to invoke the module’s function calculateShippingCost(), which will result in error because this function was not exported and remained private.

NOTE: When you have the inline script in the HTML file, you should use type="module" to make sure that the Traceur transpiles it to ES5. Without it, the browser that don’t support the let keyword (line 14) and arrow functions (line 15) would complain.

To see this code in action you need to serve it using some Web server. I use WebStorm IDE for development, which comes with embedded Web server. Lets run moduleLoader.html in Google Chrome and open Chrome Developer Tools. This is my Chrome browser looks after I clicked on the button Load the Shipping Module:


Look at the XHR tab in the middle of the window. The HTML page has loaded shipping.js after I clicked on the button. The size of this file is small and making an additional network call to get it seems like an overkill. But if the application consists of 10 modules 500KB each, modularization with lazy loading makes sense.

At the bottom, on the console tab you see the message from the script in moduleLoader that the shipping module was loaded. Then it calls the function from ship() from the shipping module, and generates an error trying to call the function calculateShippingCost() as expected.

In the real-world projects you should integrate transpiling in the project build, but I just wanted to illustrate the ease of the transpiling in the Web browser without any additional preparations. Transpilers allow you to start programming in ECMAScript today.

Written by Yakov Fain

May 30, 2015 at 3:26 pm

Posted in ES6

Started working on the Core Angular 2 book

with 13 comments

Over the past three years my colleagues and I prepared and delivered multiple trainings “Modern Web Development with AngularJS and Java“.  We felt pretty comfortable with the framework, and the training  was structured around building a sample Online Auction app with AngularJS on the front and Java EE on the back. During the last year we’ve developed and deployed in prod the Easy.Insure app using Google Dart and AngularDart.  So AngularJS became our framework of choice. When Google announced a complete re-write of the AngularJS, we were not disappointed. Angular 2 will make this great framework even better.


I’ll be writing this book with my colleague (and co-instructor) Anton Moiseev. This is going to be a tough project because Angular 2 is in Alpha now, and the API changes weekly, literally! I had this experience in 2006 while writing with my colleagues on a book on Adobe Flex 2, which went through one Alfa and three Beta versions while we were working on the book. We had to re-write code samples multiple times. It was a challenging but interesting project. Now we should do it again. It goes without saying that this book we’ll also write in a plain text editor using the Asciidoc markup and Asciidoctor for generating the HTML and PDF versions.

We want to thank Manning Publications for accepting our book proposal. Below is a short version of Table of Contents. So far only the Appendix on EcmaScript 6 is written, but by the end of July we should have the first three chapters ready as well.

1. Introducing Angular 2
  The landscape of client-side development
The history of Angular
Why choosing Angular 2
Architecture of Angular 2 applications
Introducing a sample Online Auction

2. TypeScript as a language for Angular applications
TypeScript as a superset of ECMAScript 6

3. Getting started with Angular
Creating your first single-page application
Data binding
Setting up the development environment for Angular 2 applications
Hands-on: Getting started with Online Auction

4. Registering and creating objects
The Dependency Injection pattern
Angular Modules
Hands-on: Modularizing Online Auction

5. Navigation with Component Router
Changing views
Hash-based navigation
Deep-linking with HTML5 History API
Passing Parameters to Components
Authentication and the role-based navigation
Lazy-Loading Modules
Hands-on: Adding navigation to Online Auction

6. Bringing Together Data and Views with Data Binding
Connecting UI to the data
Benefits of data binding
Unidirectional vs. two-way data binding
Change detection
Data Binding in Templates
Hands-on: Binding data to views in Online Auction

7. User Interaction via Forms
Data entry
Form controls
Data-Driven Forms
From UI-driven to data-driven forms
Form validation
Hands-on: Offering products for sale

8. Communicating with Servers
Asynchronous HTTP requests
Working with RESTful services
Using WebSockets
Hands-on: Pushing bid notifications to the clients

9. Testing Angular applications
Developing without a compiler
Test runners
Testing frameworks
Working with mock objects
Troubleshooting Angular applications
In-browser debugging
Hands-on: Testing Online Auction

10. Deploying Angular Applications
Configuring Web servers for single page applications
Supporting HTML5 History API
Proxying HTTP requests
Cross-origin resource sharing
Hands-on: Deploying Online Auction

Appendix A. JavaScript Implementation of ECMAScript 6
The Scope of a Variable
Arrow functions
Rest parameters
Code conversion from ES6 to ES5 with Babel

Appendix B. Web Components
Shadow DOM
Custom Elements
HTML Imports
Using Web Components in Angular
Using Polymer elements

Update. The book title has changed to “Learn Angular 2″.

Written by Yakov Fain

May 28, 2015 at 5:32 pm

Posted in Angular2, AngulerJS

Be careful with authorization servers

leave a comment »

These days people are accustomed to logging in to various Web sites using third-party authorization services. Do you want to login using your Facebook or Twitter account? In technical terms, this means that you are being offered to delegate the process of authorization to a third-party service offered by Facebook, Twitter or other big guys.

You’re sick and tired of creating and remembering dozens of IDs/passwords for all theses online services. Please, please login me quickly using whatever service you want. Most of such services are implemented with OAuth protocol, which allows to use the user’s account on some other servers to authorize you for accessing someone’s Web site. The good part is that OAuth servers do not reveal your id/password, but perform the authorization returning a special encoded token that will be used as you temporary passcard. The access to your Facebook or Twitter account will be limited.


The concept of giving a limited access to a resource is easily explained to rich people, who have these fancy cars with the ignition key that includes a removable small key so you can lock the glove compartment (full of diamonds) while giving a large key to a valet parking attendant. If you’re not that rich yet, take a look at this image:


Say you are visiting a Web site xyz.com, with offers you login with one of your social networks’ account. Creators of xyz.com must reveal what exactly they will be able to do with your credentials. It’s great that they won’t be able to login to your Twitter account, but will they be able to tweet on your behalf or start following people? Always read text on such login windows before clicking on that easy-to-login button.

I’ll give you a couple of examples. Here’s how Right Relevance offers you to login to their site:


With all my respect to Right Relevance for their good technical content, I wouldn’t want them to post tweets for me. Thanks, but no thanks.

Here’s another one. In April I was speaking on OAuth authorization at a Java conference in Moscow, Russia. In the evening I went to see a show in a popular theatre, which offered a free Wi-Fi hotspot. Nice! When I tried to connect to this spot from my phone I got this message:


Thank you, Hot Wi-Fi, but you’re not that hot for letting you tweet for me. Besides, it’s not polite to browse the Internet while watching a play with famous actors.

One more example, and I’ll let you go. This morning I’ve received an email that someone I know sent me a private message via a social network called Zorpia. I don’t know where are these people learning about such services, really. Anyway, you don’t have to be a rocket scientist to guess what Zorpia wants for showing me that private massage:


No, for some reason I don’t want you to manage my contacts. I frequently get emails that start like this: “John Smith is updating his contact information at the social network xxx.com and asks you to login and update your cell phone number there”. Needless to say that xxx.com starts with offering me to login with one of the popular OAuth servers, and I’d say “No”.

Don’t blame the OAuth protocol, which has all provisions for restricting the access for these third-party applications. There is a special scope parameter that allows to specify what a third-party app can do on your behalf. For example, here’s the description of the scope parameters for the developers who want to delegate authorization to Google’s OAuth servers.

Here’s my message to you: “Think twice before letting some Web application to delegate the authorization process to someone else.” Read the fine print!

Written by Yakov Fain

May 28, 2015 at 12:30 pm

Posted in User Experience, Web

ECMAScript 6, block-level functions, and the strict mode

leave a comment »

I was preparing code samples for my ECMAScript 6 (ES6) workshop. ES6 has tons of new language features and programming in the next version of JavaScript is a lot of fun. In particular, ES6 supports block-level functions, so the following code should produce the error “doSomething is not defined”.

    function doSomething(){
      console.log("In doSomething");


And it does if you test it in ES6 Fiddle:


But the best part about ES6 is that you can use it today in your real world projects. Just run it through one of the transpilers, which will convert ES6 to ES5 code ready for deployment in all existing Web browsers. Let’s see how the Babel handles my block-level function:


As you can see, Babel renamed my function to _doSomething, so doSomething is not defined, which is correct.

The Traceur transpiler did pretty much the same trick, and doSomething is not defined:


Now let’s run the same code in the console of the developer’s edition of FireFox, which doesn’t support block-level functions. It behaves differently. Because of the hoisting, the declaration of the function doSomething has been moved to the top of the script and it is defined and works.


Google Chrome (allegedly supports block-level functions) also applies hoisting and invokes doSomething (stable and experimental JavaScript features were enabled). Something is broken here. After quick search I found this ES5 recommendation that in strict mode programmers shouldn’t declare functions in a statement context (ny statement they meant block). Let’s use strict mode and try it again in FireFox:


In strict mode this code gives a syntax error in FireFox. Chrome, Babel, and Traceur still produce “doSomething is undefined” in strict mode. It’s not the end of the world, but get prepared for inconsistent results.

Written by Yakov Fain

May 14, 2015 at 10:22 pm

Posted in ES6, javascript


Get every new post delivered to your Inbox.

Join 175 other followers