Yakov Fain's Blog

My notes about everything in IT

Getting familiar with Angular 2 Dependency Injection

leave a comment »

My Angular 2 blogging series continues and today’s I’ll present you a high level overview of Dependency Injection (DI) in Angular 2.

Any Angular 2 application is a collection of components, directives, and classes that may depend on each other. While each component can explicitly instantiate its dependencies, Angular can do this job for you by using its Dependency Injection mechanism.

I’ll explain you how Angular 2 does it, but first let’s make sure that we are not confusing DI as a design pattern vs a specific DI implementation as the same design patterns can be implemented differently depending on the software you use. For example, in the Java world there are multiple implementations of DI. For example, Spring Framework has the most popular DI container. Java EE has its own implementation of Resource Injection and Context Dependency Injection. Angular 2 has its own implementation of the DI pattern.

DI and IoC Patterns

Imagine a fulfillment center that ships products. An application that keeps track of shipped products may create a product object and invoke a function that creates and saves a shipment record:

var product = new Product();

The function createShipment() depends on the existence of an instance of the Product object. In other words, the function createShipment() has a dependency: Product. The function itself doesn’t know how to create it. The calling script should somehow create and inject this object as an argument to the function createShipment().

But the thing is that the class Product should be implemented by the offshore team, and it’s not ready yet (oh, those Indians!). So you decided to provide a MockProduct as a substitute for an actual Product until the offshore team catches up.

In our two-line code sample it’s an easy change, but what if the function createShipment() has three dependencies (e.g. product, shipping company, and fulfillment center) and each of these dependencies has it’s own dependencies? Now creating a different set of mock objects for createShipment() would need a lot more manual code changes. Would it be possible to ask someone to create instances of dependencies (with their dependencies) for us?

This is what the Dependency Injection pattern is about: if an object A depends on the object of type B, the object A won’t explicitly instantiate the object B (as we did with the new operator above), but rather will get it injected from the operational environment. In other words, the object A just needs to declare, “I need an object of type B, could someone please give it to me?” The words of type are important here. The object A does not request a specific implementation of the object and will be happy as long as the injected object is of type B.

The Inversion of Control (IoC) is a more general pattern than DI. Rather than making your application to use some API from a framework (or a software container), the framework will create and supply the object(s) that the application needs. The IoC pattern can be implemented in different ways and DI is one of the ways to provide required objects. Angular plays a role of the IoC container and can provide the required objects according to your component’s declarations.

Benefits of DI and how Angular Does It

Angular offers a mechanism that helps registering and instantiating component dependencies. In short, DI helps in writing code in a loosely coupled way and makes your code more testable and reusable.

Loose coupling and reusability

Say you have a ProductComponent that gets product details using the ProductService class. Without DI your ProductComponent needs to know how to instantiate the class ProductService. It can be done by multiple ways, e.g. using new, calling getInstance() on some singleton object, or maybe invoking a createProductService() on some factory class. In any case ProductComponent becomes tightly coupled with ProductService.

If you need to reuse the ProductComponent in another application that uses different service for getting product details, you’d need to modify the code (e.g. productService = new AnotherProductService()). DI allows to decouple application components by sparing them from the need to know how to create their dependencies. Consider the following ProductComponent sample:

providers: [ProductService]
class ProductComponent {
product: Product;

  constructor(productService: ProductService) {

     this.product = productService.getProduct();

In Angular applications written in TypeScript you do this:

a) Register an object(s) for DI by specifying a provider(s), which is an instruction to Angular on how to instantiate this object when the injection is requested
b) Declare a class with a constructor that has the argument(s) of types that match provider’s types

When Angular sees a constructor with an argument of a particular type, it starts looking for a provider that specifies HOW to instantiate an object of this type. If the provider’s found in the current component, Angular will use it to instantiate an object and inject it to the component via its constructor.

Angular 2 inject object only via constructor’s argument, which greatly simplifies this process comparing to Angular 1.

In the above code snippet the line providers:[ProductService] is a shortcut for provide(ProductService, {useClass:ProductService}). We’re instructing Angular to provide a token ProductService using the class of same name. Using the method provide() you can map the same token to a different class (e.g. to emulate the functionality of the ProductService while someone else is developing a real service class).

Now that we’ve added the providers property to the @Component annotation of the ProductComponent, Angular’s DI module will know that it has to instantiate the object of type ProductService.

The ProductComponent doesn’t need to know which concrete implementation of the ProductService type to use – it’ll use whatever object was specified as a provider. The reference to the ProductService object will be injected via the constructor’s argument, and there is no need to explicitly instantiate ProductService inside ProductComponent. Just use it as in the above code, which calls the service method getDetails() on the ProductService instance magically created by Angular.

If you need to reuse the same ProductComponent in a different application with a different implementation of the type ProductService, change the providers line, for example:

providers: [provide(ProductService, {useClass:AnotherProductService})]

Now Angular will instantiate AnotherProductService, but your code that was using the type ProductService won’t break. In our example using DI increases reusability of the ProductComponent and eliminates its tight coupling with ProductService. If one object is tightly-coupled with another, this may require substantial code modifications should you want to reuse just one of them in another application.


DI increases testability of your components in isolation. You can easily inject mock objects where if their real implementations are not available or you want to unit-test your code. Say you need to add a login feature to your application. You can create a LoginComponent (it would render ID/password fields) that uses a LoginService component, which should connect to a certain authorization server and check the user’s privileges. The authorization server has to be provided by a different department (oh, those Russians), but it’s not ready yet.

You finished coding the LoginComponent, but you can’t test it for reasons that are out of your control, i.e. dependency on another component developed by someone else.

In testing we often use mock objects, which mimic the behavior of real objects. With a DI framework you can create a mock object MockLoginService that doesn’t actually connect to authorization server but rather has hard-coded access privileges assigned to the users with certain ID/password combinations. Using DI you can can write a single line injecting the MockLoginService into your application’s Login view without the need to wait till the authorization server is ready.


Later on, when that server is ready you can modify the providers line so Angular would inject the real LoginService component as shown below.

Injectors and Providers

Angular 2 has such concepts as injectors and providers. Each component has an Injector capable of injecting objects into other components. Any Angular application is hosted by some root component, so you always have a root injector available. An injector knows how to inject one object of the specified type into the constructor of another.

Providers allows you to map a custom type (or a string) to a concrete implementation of this type (or a value). We’ll be using ProductComponent and ProductService for all code samples in this chapter, and if your application has only one implementation of a particular type (i.e. ProductService), specifying a provider can look like this:


IMPORTANT: The providers property is specified inside the @Component annotation, which allows Angular to register the class for future injection. No instance of the ProductService is created at this point. The providers line instructs the injector as follows: “When you’ll need to construct an object that has an argument of type ProductService create an instance of the registered class for injection into this object”.

The shorter notation of the above provider statement looks like this:


If you need to inject a different implementation of a particular type, use the longer notation:

provide(ProductService, {useClass: MockProductService});

Now we’re giving the following instruction to the injector:
“When you’ll need to inject an object of type ProductService into a constructor’s argument create an instance of the class MockProductService”.

The injector knows what to inject, and now we need to specify where to inject the object. In TypeScript it comes down to declaring a constructor argument specifying its type. The following line shows how to inject the object of type ProductService into the constructor of some component.

constructor(productService: ProductService)

The constructor will remain the same regardless of which concrete implementation of ProductService was specified as a provider. Below is a sample sequence diagram of the injecting process.


Injection With TypeScript vs ES6

TypeScript simplifies the syntax of injection as it doesn’t require using any DI annotations. Specifying the type of the constructor’s argument is all that’s needed:

constructor(productService: ProductService)

There is one requirement for the above line to work though: the TypeScript compiler need to be configured with the option “emitDecoratorMetadata”: true. With this option the generated JavaScript code will contain the metadata information about the argument type so Angular will know which type of the object to inject.

I use the SystemJS polyfill for on-the-fly TypeScript transpiling, we can add the following TypeScript compiler’s option in the configuration file for SystemJS:

typescriptOptions: {
  "emitDecoratorMetadata": true

If you’d be writing the class in ES6, its constructor would need the @Inject annotation with explicit type:

constructor(@Inject(ProductService) productService)

How to Create a Provider

The function provide() returns an instance of the Provider object, and this function can be called in different ways because the object creator can be a class or a factory (with or without dependencies).

* To map a type to an instance of a class use the function provide() where the second argument is an object with the useClass property.

* If you have a factory function that instantiates objects based on certain criteria use the function provide(), where the second argument is an object with the useFactory property, which specifies a factory function (or a fat arrow expression) that knows how to instantiate required objects. The factory function can have an optional argument with dependencies, if any.

* To provide a string with simple injectable value (e.g. a URL of a service ) use the function provide() where the second argument is an object with the useValue property.

In the next blogs I’ll write a sample app to illustrate the use of useClass, useFactory, and useValue.

I’m co-authoring the book “Angular 2 Development with TypeScript“, and Manning offers the electronic version of whatever content is ready (138 pages are available). Starting on January 3rd, we’ll also teach an online class on Angular 2, and you can use the promo code blogreader to get $50 off the price.

Written by Yakov Fain

November 23, 2015 at 6:48 pm

Posted in Angular2, TypeScript

Angular 2: Passing Data to Routes

leave a comment »

In the previous blog I did a high-level overview of Angular 2 router and wrote a basic routing application that demonstrated displaying different components in a predefined area of the window. We often need not only display a component, but also pass some data to it. For example, if we navigate from the Home to the Product Detail route we need to pass the product ID to the destination route.

Angular wraps the data given to a route into an object of type RouteParams. There is also a class RouteData that can be used to pass additional data to a route from the @RouteConfig section. I’ll illustrate the use of both classes by modifying the app from the previous blog.

Using RouteParams

When the user navigates to the ProductDetail route, we need to pass the product ID to display details of the particular product. Let’s modify the code so the RootComponent can pass the product ID to ProductDetailComponent. The new version of this component will be called ProductDetailComponentParam and it’ll use the directive RouteParams:

import {Component} from 'angular2/angular2';
import {RouteParams} from 'angular2/router';

    selector: 'product',
    template: `<h1 class="product">Product Detail for Product: {{productID}}</h1>` , // 1
    styles: ['.product {background: cyan}']})
export class ProductDetailComponentParam {
    productID: string;
    constructor(params: RouteParams) { // 2
        this.productID = params.get('id'); // 3

1. Display the received product ID using binding.

2. The constructor of this component requests Angular to inject the object RouteParams, which contains all parameters that are passed to this component. In TypeScript you just need to declare the argument specifying its type, and Angular will know how to instantiate and inject this object.

3. Get the value of the parameter named id and assign it to the class variable productID, which is used in template via binding.

Now let’s see how we can change @RouteConfig and router-link to ensure that the value of the product ID will be passed to the component ProdutDetailComponentParam if the user choses to go this route. We’ll do the changes in the file main.ts:

import 'reflect-metadata';
import 'zone.js'; // 1

import {Component, bootstrap, provide} from 'angular2/angular2';
import {HomeComponent} from './components/home'; // 2
import {ProductDetailComponentParam} from "./components/product_param";

        LocationStrategy, HashLocationStrategy} from 'angular2/router';

    selector: 'basic-routing',
    template: `<a [router-link]="['/Home']">Home</a>
               <a [router-link]="['/ProductDetail', {id: 1234}]">Product Details</a> // 3
    directives: [ROUTER_DIRECTIVES]})
    {path: '/',            component: HomeComponent,               as: 'Home'},
    {path: '/product/:id', component: ProductDetailComponentParam, as: 'ProductDetail' }]) // 4
class RootComponent {}

bootstrap(RootComponent, [ROUTER_PROVIDERS,
  provide(LocationStrategy, {useClass: HashLocationStrategy})]);

1. Angular asynchronously modifies the values of properties participated in binding. In our case, after the user choses to open the product detail component, the value of the variable productID changes and its bindings need to be updated. The library zone.js will automatically sync up all the bindings and watchers in the entire component tree of the application.

2. I kept my components in the _components_ directory and need import them from there.

3. This time there are two elements in the array given to router-link. The first one is the name of the route and the second is a JavaScript object containing a name/value pair that represents the parameter to be passed to the /ProductDetail route. For simplicity we’ve hardcoded the id to be 1234, but if we had a variable product pointing to the corresponding object, we could have written {id: product.id} here.

4. The path property has an additional fragment /:id. The name of this URL fragment must match the name of the parameter property used in router-link. Angular will construct the URL fragment /product/1234 for this ProductDetail route. Note that we still use the same route name in router-link even though it points not to the ProductDetailComponent but to ProductDetailComponentParam.

The following screenshot shows how the product detail view will be rendered in the browser:


Note the URL. Angular router replaced the path /product/:id with /product/1234.

Let’s overview the steps that Angular did under the hood for rendering the main page of the application:

1. Check the the content of each router-link to find the corresponding routes configurations.

2. Modify the URL fragments the parameters with actual values where specified.

3. Build the actual <a href=””> tags that the browser understands.

The next screenshot shows a snapshot of the home page of our application with the Chrome Dev Tools panel open.


Since the path property of the Home route contains just the slash, Angular simply removed it – a single slash base URL of the page. But the anchor under Product Details link is already converted into a regular HTML tag. When the user will click on the Product Details link, the router will attach a hash sign and add /product/1234 to the base URL so the absolute URL of the Product Detail view will become http://localhost:8080/#/product/1234.

Using RouteData

While most of the times parent components will be passing data to their children, Angular also offers a mechanism to pass additional data to components at the time of the route configuration. For example, besides the data that a component needs for implementing application logic, we may need to pass a flag indicating if the application runs in production environment or not. This can be done by using the data property of the @RouteConfig annotation. For example, our ProductDetail route can be configured as follows:

    {path: '/product/:id', component: ProductDetailComponentParam,
     as: 'ProductDetail', data: {isProd: true}}])

Accordingly, the constructor of the ProductDetailComponent will need an extra argument of type RouteData:

export class ProductDetailComponentParam {
    productID: string;
    constructor(params: RouteParams, data: RouteData) {
        this.productID = params.get('id');

        console.log(`Is this prod environment: ${data.get('isProd')}`);

Passing data to a route with RouteData is not an alternative to RouteParams. While RouteParams is used to pass the data from one route to another using based on the user’s selections (e.g. show details of the selected product), RouteData can come handy when you need to pass some data to a route during the configuration phase, e.g. is it a production or QA environment, should the user have administrator’s privileges, or what URL of use for the product service.

To see this application in action follow this plank and press the button Run. For simplicity, all the code is located in one file main.ts. Also, I imported the dev version of Angular in the index.html that includes such libraries as zone.js and reflect-metadata, so there is no need to import them separately.

Stay tuned for more Angular 2 blogs. My other Angular-related blogs are here . Manning started publishing drafts of our book “Angular 2 Development with TypeScript“.

Written by Yakov Fain

November 11, 2015 at 6:48 pm

Posted in Angular2, TypeScript

Angular 2 Router: High-Level Overview

with 5 comments

Angular 2 framework (currently in Alpha 46) offers a simple way to implement client-side navigation for Single-Page Applications (SPA). The new component router allows you to configure routes, map them to the corresponding components, and arrange user’s navigation in a declarative way. While working on a routing chapter for the upcoming book “Angular 2 Development with TypeScript” I created a number of small applications illustrating various routing scenarios:

– Configuring routes in the root component
– Configuring routes in both root and child components
– Passing parameters to routes
– Using routing with both Hash- and History API-based strategies
– Using auxiliary (independent) routes
– Routing with lazy-loading of components

All of the above works, but in this blog I’ll do a high-level overview of Angular 2 routing and will show you a basic working example where the routing is configured in the root component of the application.

When you visit any Web page the location bar of your browser shows a URL (see, you already learned something new!). The URL consists of a protocol, domain name, port, and in case of GET requests may have parameters after the question mark:


If you change any character in the above URL and press Enter, this will result in sending a request to the server and page refresh, which is not what we want in SPA. In SPA, we want to be able to change a URL fragment that won’t result in the server request, but would update a portion of the Web page based on the JavaScript code that is already loaded to the browser.

Many years ago browsers started supporting a hash-sign (#) in the URLs, for example:


Any modifications to the right of the hash tag don’t trigger requests to the server, hence we can map these fragments to the client-side component to be rendered in the designated area of the Web page (in Angular 2 it’s identified by the tags <router-link></router-link>).

Then browsers started implementing HTML5 APIs, which includes History API that allows programmatically support the Back and Forward buttons as well as modify a URL fragment using the pushState() method. The history of all user’s navigations would be
stored on the client.

Angular 2 supports both location strategies using its classes HashLocationStrategy or PathLocationStrategy sparing you from adding the hash sign to the URL or calling pushState(). You just need to choose which strategy to use. I prefer hash-based navigation because a) it’s supported by all the browsers and b) History API-based navigation is unstable at this point.

Now let’s get familiar with the main players of Angular 2 navigation:

* RouterOutlet – a directive that serves as a placeholder within your Web page where the router should render the component

* @RouteConfig – an annotation (metadata) to map URLs to components to be rendered inside the <router-outlet></router-outlet> area

* RouteParams – a service for passing parameter to a component rendered by the router

* RouterLink – a directive to declare a link to a view and may contain optional parameters to be passed to the component

In a typical scenario, you’ll be implementing navigation in your application by performing the following steps:

1. Configure the router on the root component level to map the URL fragments to the corresponding named components. If some of the components expect to receive input values, you can use route params.

2. Add the property directives: ROUTE_DIRECTIVES to the @Component annotation. This will allow you to use the custom tag <router-outlet></router-outlet> for directive RouterOutlet, the property router-link for RouterLink et al.

3. Define the viewport where the router will render components using <router-outlet></router-outlet>.

4. Add the HTML anchor tags with bounded [router-link] properties (square brackets is syntax for property binding), so when the user clicks on the link the router will render the corresponding component. Think of [router-link] as a client-side replacement for the href attribute of the HTML anchor tag.

Let’s illustrate these steps in the code. Say we need to create a home page for an online store that would display the inventory of products. Clicking on a product would need to bring a view with product details. Our simple application (I use TypeScript) will have a RootComponent that will display two links Home and Product Details at the top of the page. The application should render either HomeComponent or ProductDetailComponent depending on which link the user clicks.

The HomeComponent will render the text “Home Component” on the red background, and the ProductDetailComponent will render “Product Detail Component” on cyan. Initially the Web page should display the HomeComponent as shown below.


After the user clicks on the Product Details link the router should display the ProductDetailComponent as shown on the next screenshot. Note the hash portion in the URL (this URL is bookmarkable):


The main goal of this exercise is to get familiar with the router, so our components will be very simple. Below is the code of HomeComponent:

import {Component} from 'angular2/angular2';

    selector: 'home',
    template: '<h1 class="home">Home Component</h1>',
    styles: ['.home {background: red}'],
export class HomeComponent {}

The code of the ProductDetailComponent will look similar, but instead of red the property styles will define the cyan background:

import {Component} from 'angular2/angular2';

    selector: 'product',
    template: '<h1 class="product">Product Detail Component</h1>',
    styles: ['.product {background: cyan}']
export class ProductDetailComponent {}

The [RootComponent] will define the routing of this application, and its code is shown next.

import 'reflect-metadata';

import {Component, bootstrap, provide} from 'angular2/angular2';
import {HomeComponent} from './components/home';
import {ProductDetailComponent} from "./components/product";

        LocationStrategy, HashLocationStrategy} from 'angular2/router'; // 1

    selector: 'basic-routing',
    template: `<a [router-link]="['/Home']">Home</a>
              <a [router-link]="['/ProductDetail']">Product Details</a>
              <router-outlet></router-outlet>`, // 3
    directives: [ ROUTER_DIRECTIVES] // 4
    {path: '/', component: HomeComponent, as: 'Home'}, // 5
    {path: '/product/', component: ProductDetailComponent, as: 'ProductDetail'  }
class RootComponent{}

bootstrap(RootComponent, [ROUTER_PROVIDERS, 
       provide(LocationStrategy, {useClass: HashLocationStrategy})]); // 6

1. First we import all router-related directives and classes from ‘angular2/router’. The location strategy defines how the application will interact with browser’s URL. We use HashLocationStrategy, which means that if we configure the router with the fragment ‘/product’, Angular will add the hash sign and this fragment to the base URL (note the URL on the screen snapshot). The browser will treat the fragment after the hash sign as an identifier of a specific fragment of the Web page.

2. The first anchor tag has the property router-link bound to the route named Home. The square brackets on the left are for property binding. The square brackets on the right represent an array with one element (e.g. ‘/Home’), and we’ll show you examples of array with two or more elements later in this chapter. The second anchor tag has the property router-link bound to the route named ProductDetail. These routes’ names are specified in the @RouteConfig annotation.

3. The pair of tags <router-outlet></router-outlet> specifies the area in the page where the router will render one of our components. The value in the router-link will be matched with the route name from @RouteConfig. In our case <router-outlet></router-outlet> represents the area below the anchors.

4. We’re declaring that our component will use router directives.

5. The routes are configured here. This is where we map the URL fragments (path) to application components. We also give each route a name, which is used with router-link. Naming routes is handy if you do refactoring. You may decide to rename HomeComponent into HomeComp, but since we didn’t use the actual component name in any of the router-link properties, renaming the component will require a single line change in the @RouteConfig annotation.

6. During the application bootstrap we specify dependencies of the RootComponent in the square brackets. Providers are used to register objects for dependency injection that I’ll cover in a separate blog. At this point it suffice to know that we want Angular to instantiate the router objects using the definitions from ROUTER_PROVIDERS. While the default location strategy is PathLocationStrategy, we’re using the class HashLocationStrategy for hash-based routing.

NOTE: In versions prior to Alpha 46 you could manually crete an instance of the route in the @RouteConfig section, e.g. new Route({path: ‘/’, component: HomeComponent, as: ‘Home’}). This syntax will generate an error starting from Aplha 46.

To see this application in action follow this plunk and click on the button Run.

That’s all for now. Stay tuned for more Angular 2 blogs. My other Angular-related blogs are here.

Written by Yakov Fain

November 2, 2015 at 7:22 pm

Posted in Angular2, TypeScript

Angular, TypeScript, SystemJS, and Browser Cache

with 7 comments

I was writing a small app in Angular 2 in TypeScript with the on-the-fly transpiling by SystemJS. I needed to implement a router that would switch between the Home and ProductDetail views in a single page app.  The root component had two links and was supposed to render either Home or ProductDetail components depending on which link the user clicks. Angular 2 offers a pretty elegant syntax for this:

    selector: 'basic-routing',
    directives: [ ROUTER_DIRECTIVES], 
    template: `<a [router-link]="['/Home']">Home</a>
              <a [router-link]="['/ProductDetail']">Product Details</a>
    {path: '/',        component: HomeComponent, as: 'Home'}, 
    {path: '/product/', component: ProductDetailComponent, as: 'ProductDetail'  } 
class RootComponent{}

Configure the router to map the component to a URL, use property binding in the form of [router-link], and specify the router outlet, where the content of one or the other component should be rendered. Nice and easy, isn’t it? Then I created a HomeComponent to render the text ‘Home Component’ , copy-pasted the code into ProductDetailComponent and started the app in the browser.

Running the app properly rendered the text Home Component, but when I clicked on the second link, nothing happened – the text Home Component remained in the browser window. Opened the code of the ProductDetailComponent. Oops… Forgot to change the text for rendering while copy-pasting – it still had ‘Home Component’. No biggies. Replaced it with ‘Product Detail Component’ and re-ran the app. Nothing changed. I still see Home Component no matter what link I click.

So what do we do with this nice syntax with Angular binding and TypeScript annotations? There is nothing to debug there. We need to debug the actual ES5 code that runs in the browser. Here’s the snapshot of my application window (on the left) after I clicked on the Product Detail link (Chrome Dev Tools panel is on the right):


Note that Angular router properly formed the URL for the product view. The template property in the file product.ts has the right content: ‘Product Detail Component’. Now let’s take a look at the content of the file product.ts!transpiiled, which was auto-generated by SystemJS:


This file was not regenerated and still has the ‘Home Component’ in the template property! Apparently, changing the string content is not a good enough reason for SystemJS to re-run the TypeScript transpiler and the browser used its cached version. Running the same example in FireFox worked as expected – its cache was clean so fresh ES5 files were generated by SystemJS.

Chrome Dev Tools has an option Disable Cache while Dev Tools open, and this would clear the cache on the page refresh. But if you want the browser cache to be refreshed even if the Dev Tools are not open, add the following lines between the head tags in your HTML file:

  <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
  <meta http-equiv="Pragma" content="no-cache">
  <meta http-equiv="Expires" content="0">

Manning opened the MEAP program for our upcoming book “Angular 2 Development with TypeScript”, where JSPM, SystemJS and TypeScript development is covered in greater details.

Written by Yakov Fain

October 23, 2015 at 12:49 pm

Posted in Angular2, TypeScript

Starting an Angular 2 project with TypeScript and JSPM

with one comment

New York City residents often say “It’s going to be a nice city when all the constructions will be finished”. The same applies to Angular 2 framework, which remains in Alpha (the latest build is 42 at the time of this writing). It has a potential to become a great framework in 2016, when the API will be stabilized and documented.

Writing code in Angular 2 is a lot simpler than in AngularJS, especially if you use TypeScript (see my blog on why writing in TypeScript here). But getting started with a new project is more complicated and requires a careful selection of tooling. in addition to a typical JavaScript project you need to take care of transpiling TypeScript and loading modules – neither of these steps can be done natively by the browsers. Hence you need introduce tooling into your develop-deploy process. For reasoning of using TypeScript read this blog.

Earlier this year I wrote a blog that included a scary list of tools that today’s JavaScript developers may use. In an effort of minimizing the number of required tool we settled on npm (for both installing packages and build scripts) and JSPM (a package manager that comes with the module loader SystemJS that comes with TypeScript transpiler). These are the steps that should be done before you start writing your Angular 2 app in TypeScript:

In the command window run the following npm command (install Node.js runtime if you don’t have npm):

1. Install JSPM globally on your computer (-g means global). It comes with SystemJS:

npm install jspm -g

2. Create a folder for your project, go there and ask jspm to generate all required configuration files:

jspm init

This command will ask you 8 question regarding the required configuration. Accept the defaults for the first 7 questions, but for the question about transpiler, enter typescript. After running this command in your folder you’ll find the new files config.js and package.json as well as the subfolder jspm_packages.

3. Install Angular 2 in your project folder and all required dependencies:

jspm install angular2 core-js css reflect-metadata

This command will download all of the above libraries inside the folder jspm_packages and will modify the content of the file config.js

4. Install an http server that will be serving your app to the browser:

npm install http-server -g

5. Create the file index.html with the following content:

<!DOCTYPE html>
  <script src="//cdn.rawgit.com/systemjs/systemjs/0.19.4/dist/system.js"></script>
  <script src="//code.angularjs.org/2.0.0-alpha.40/angular2.js"></script>
    transpiler: 'typescript',
    map: {typescript: '//cdn.rawgit.com/Microsoft/TypeScript/v1.6.2/lib/typescript.js'}


This code loads SystemJS and Angular (I used the build Alpha 40) and tells SystemJS to load the TypeScript 1.6.2 compiler from CDN, and load the file main.ts , which is shown next.

6. The Typescript file main.ts is your entry point to the application. It can import other files, but this would be a subject for a separate blog post. This is what you should enter in main.ts:

import {Component, bootstrap} from 'angular2/angular2';

  selector: 'hello-world',
  template: `<h1>Hello {{ name }}!</h1>`
class HelloWorldComponent {
  name: string;

  constructor() {
   this.name = 'Angular 2';


The @Component annotation is all you need to to turn a class into a component. The selector property defines a name of the tag that represents this component in the HTML file. The template property defines the HTML to render. In this example the value of the variable name will be evaluated and inserted in the greeting using Angular binding.

7. Start your http server by entering http-server in the command line from your project directory and enter http://localhost:8080 in your Web browser you should see a Web page that reads Hello Angular 2! Here’s how it’s rendered in my Chrome browser with Developer Tools panel open:

As you see the TypeScript compiler was downloaded as a part of your application and the transpiling of the code was done on the fly.

In this simple example I didn’t install any TypeScript related tool to keep this example IDE-agnostic. But we do use IDEs and additional install of the tsd (type definition manager) and DefinitelyTyped library would be required as well so the context-sensitive help for your code and all third-party JavaScript libraries would be available.

I like the fact that JSPM and SystemJS are written by the same developer (Guy Bedford). With these tools the configuration process is automated, modules of different formats are seemlesly loaded, TypeScript is automatically transpiled, duplicate dependencies are not being loaded, and we can can get dependencies from multiple repositories. All this comes at a price of a couple of seconds delay before you see your page loaded in a browser.

JavaScript developers are spoiled by seeing their latest code changes deployed and rendered instantaneously. Coming out of a Java project that required minutes to see my code changes in action, I can live with these extra couple seconds. But opening the configuration files auto-generated by JSPM still gives me light goose bumps. There is too much stuff in there. Again, that Java project had Maven build scripts with thousands lines of code, so I can live (for now) with 300 lines in config.js in a Hello World project, but the search of the configuration holly grail continues…

Manning opened the MEAP program for our upcoming book “Angular 2 Development with TypeScript”, where JSPM, SystemJS and TypeScript are covered in greater details.

Written by Yakov Fain

October 13, 2015 at 4:21 pm

Posted in Angular2, TypeScript

Why writing JavaScript applications in TypeScript

with 3 comments

JavaScript is the language of the Web. There is no other language that can run literally on any old or new device connected to the Internet. On the other hand, there are dozens of languages that compile (a.k.a. transpile) to JavaScript. Why not just writing JavaScript applications in JavaScript? Let me start with analogy with Assembly.

Programs written in a particular flavor of Assembly language run on any device that have a CPU that understand it. See the shortcoming comparing to JavaScript? An Assembly program can’t run on any device, but on any device with a specific CPU architecture. Still, why not writing all the code for a specific platform in Assembly? Why use Java, C#, Python or C++?

We want to be productive. Vast majority of the programmers want to be as far as possible from the bare bone metal. Let compilers and virtual machines convert our programs to the machine code.

We want to be productive in writing JavaScript as well.

Compilers convert the source code into a byte code or a machine code. Transpilers convert a source code of a program in one language into a source code in another one.

You can think of any programming language (other than a machine code) as a syntactic sugar added on top of a another language. While compilers just dissolve all this sugar, transpilers dissolve only a part of it.

Last year I was experimenting with the Dart language. It has a nice syntax (easy for Java and C# developers), which transpiles to to JavaScript. I like Dart, but it requires a special browser with a VM during development. The other negatives are that Dart code transpiles into a difficult to read JavaScript and doesn’t offer easy interoperability with JavaScript frameworks that coexist with the Dart code in most of the applications.

TypeScript was designed by Anders Hejlsberg who also created C#, Delphi, and Turbo C++. TypeScript is a superset of JavaScript, which means that simply renaming existing .js into a .ts file will make it a valid JavaScript code. This is almost always the case except the cases described in this blog.

The TypeScript compiler tsc is actually a transpiler that generates easy to read JavaScript. TypeScript can be compiled into the ES#, ES5, or ES6 flavor of JavaScript, which is a simple option on the command line. You can run tsc in a so called watch mode, so it watches your files for changes and automatically compiles them as soon as you save the file.

Currently I use TypeScript for writing code that uses two frameworks by Google: Angular 2 (it’s written in TypeScript as well) and Polymer.

These are some reasons for writing JavaScript code in TypeScript:

* TypeScript supports types. This allows the TypeScript compiler help developers in finding and fixing lots of errors during development before even running the app.

* Creators of TypeScript follow the ECMAScript 6 standard,and TypeScript 1.6 already supports more than a half of the ES6 syntax. Also TypeScript enriches ES6 by adding types, interfaces, decorators, class member variables (fields), generics, and the keywords, public and private (well, private is not what some might think). See the roadmap of TypeScript.

* TypeScript interfaces allow to declare custom types that will be used in your application. Interfaces help in preventing errors caused by using the objects of wrong types in your application. This feature will be dear to the hearts of Java and C# developers although TypeScript interfaces can be use not only with the implements keyword, but used for presenting object types in a special way.

* The ability to have great IDE support is one of the main advantages that TypeScript has to offer. IDEs as well as some text editors offer great context-sensitive help. The code refactoring of TypeScript is done by IDEs whereas with JavaScript it has to be done manually.

* There is a library DefinitelyTyped that includes hundreds of type definitions files for TypeScript and allows IDEs to perform type checking and offer context-sensitive help while using APIs of literally all JavaScript frameworks.

* The generated JavaScript code is easy to read and looks as a hand-written code. Even though you can generate so called source maps that allow you to debug the TypeScript code inside the browser, you can easily read generated JavaScript and find the corresponding lines in your TypeScript program.

* TypeScript comes with a separate static code analyzer, and several IDEs or text editors already use it (e.g. WebStorm, Atom, Sublime Text, Visual Studio Code, Visual Studio 2015 et al.)

Anyway, today TypeScript is my language of choice for writing the source code for Web browsers. I’m planning to write a couple of more blogs introducing TypeScript syntax. If you want to play with TypeScript, visit http://www.typescriptlang.org.

If you’re a Java developer who kept postponing learning JavaScript till better times, the time is now. You can ease into the JavaScript world via the door marked “TypeScript”.

If you’re planning to work with Angular 2 and want to see how to use TypeScript with this framework, our upcoming “Angular 2 Development with TypeScript” book may come handy.


Written by Yakov Fain

October 2, 2015 at 8:10 pm

Posted in Angular2, TypeScript

From Flex to Angular and Polymer

with 2 comments

I’ve received an email from an enterprise Flex developer who’s looking to converting a number of applications to JavaScript. He asked a number of questions, and I decided to write a brief blog with the answers. His email stared like this:

“We have a bunch of existing enterprise Flex web apps.
Since some of Flex libraries are not updated and no longer supported, first we try to find similar libraries in JavaScript and and call them via iFrame.”

Below are his questions and my answers.

1) Do you see Flex -> Angular 1 transition as smart pragmatic move, or would recommend to wait till Angular 2 comes out?

Comparing Flex and Angular is not apples to apples. Besides being an architectural framework it included a number of rich and extendable UI components, which Angular doesn’t have. Angular will definitely help you in creating a Web application taking care of the navigation between the views, binding the data to the UI, and injecting services into your components. But this is pretty much it. It doesn’t have its own component that are often needed by the enterprise developers. This is one of the reasons why we started using Google’s Polymer for GUI components.

2) Does A2 has definite advantages over A1? Is it easier and has better tooling?

Yes, it’s easier to learn as Angular architecture is simplified greatly. A2 is component based. No need to worry about different scopes. Any service is a class. No need to create controllers in a special way: a class is a controller. Dependency Injection is easier to use – only constructor injection is allowed. The GUI for the component is specified in a class annotation and can be stored in a separate file. A2 rendering is separated from the rest of the framework code, so it’ll be possible to render not only HTML, but the native UI as well (this feature is experimental for now).

As to tooling, we’re pretty happy with a combination of TypeScript, JSPM, and SystemJS. The entire app can be easily modularized. SystemJS loads modules of different formats (ES6, CommonJS, AMD). JSPM is a package manager that works with SystemJS well.

3) When will A2 be released? Is it worth waiting for?

Currently A2 is in the 35th build of Alpha. There is no official release dates, but I believe that A2 will go in Beta in October-November of this year. You can (and should) start developing in A2 today as long as the app doesn’t have to go in production this year. The API of this framework is still being changed so you may run into bugs here and there. But I’d recommend starting new projects in Angular 2.

4) Do you expect to have an easy upgrade from A1 to A2?

It may not be easy, but shouldn’t be overly complicated either. If you have resources you can upgrade existing apps to A2, but it’s not a must. You may live with two version of the app for some time.

5) When will you give an A2 class? When will your A2 book come out?

We were planning to run the A2 class online starting form the end of September, but since both my colleague/instructor/co-author and I have a day job plus a book project in the evenings, we decided to postpone the training till January.

Our book “Learning Angular 2” will be available as a part of Manning MEAP program in September. You’ll be able to buy it and get access to the drafts as we write them. So far we’ve written about 130 pages.

Now I’d like to add a brief comment about Polymer library from Google. Our company, Farata Systems, spent 9 years developing applications in Adobe Flex for different clients. Over these years we’ve created a library of smart GUI components that were not easily replaceable in JavaScript. During the last two years we were evaluating different JavaScript alternatives, but couldn’t find any that would allow us to leverage or experience and migrate our Flex components to JavaScript.

Finally, there is a light at the end of the tunnel, namely Google’s Polymer. This library comes with a set of prefabricated UI components, but what’s more important, you can create your own Web components based on it.

Being very pragmatic and careful, we’ve decided to see how difficult would be to re-create a Flex component in Polymer. Eight years ago we’ve created a combobox in Flex that could take an external data collection as a model and render its data as a grid when the user clicks on it. We gave this combobox to one of our developers, and he re-created it in Polymer relatively easily. Another developer started to work on a pilot project with Polymer and we also see good results.  What we don’t like in Polymer is the fact that it doesn’t support module loading. You have to use HTML imports. Anyway,  our recommended set of languages/frameworks is TypeScript, Polymer, and Angular 2.

In September we’re planning to publish two technical articles describing our experience with Polymer. Farata Systems is a well known name in the Flex community, and we’re going to build a good reputation in the JavaScript world as well.

Written by Yakov Fain

August 23, 2015 at 2:11 pm

Posted in Angular2, flex, javascript


Get every new post delivered to your Inbox.

Join 188 other followers