Wrote a book on Angular 2. Do I know it?

Over the last year I spent a substantial portion of my time writing a book “Angular 2 Development with TypeScript”. I wrote it with my colleague, Anton Moiseev. We are already working on real-world projects in Angular 2 for our software product SureLC that automates the work of insurance agents. We also taught multiple public and private Angular 2 workshops.

This morning after reading yet another post titled “How to learn Angular 2?”, I’ve asked myself, “Do I know Angular 2?”. The honest answer is “Kinda”. Let me explain.

First, let’s define what a developer needs to know to be productive in an Angular 2 project. I’ll color the items as the slopes marked in the ski resorts.

Green – easy Almost flat
Blue – moderate. Can get nasty is the snow is not groomed
Red – difficult, but manageable for non-experts. The slopes are steeper than blue
Black – really difficult. You have to be an expert to enjoy the ride.

Disclaimer. I can ski on black slopes, but I don’t enjoy the process. You won’t enjoy watching me going down the black slope, but I’ll arrive to the base.

skii_map

1. TypeScript. Yes, you can use other languages, but let’s get real. The framework is written in TypeScript, 90% of blog post and tutorials use TypeScript.

2. NPM package manager. America runs on Dunkin. The JavaScript world runs on packages. If a C-programmer writes a function to pad a string with spaces, JavaScript programmer tries to find an NPM package that does it and adds it as a dependency to his application.

3. Type definition files (*.d.ts). These files help TypeScript compiler understand the API of third-party libraries written in JavaScript. Starting from TypeScript 2.0 it’s relatively easy with the @types npm organization.

4. A module loader. Starting from EcmaScript 6 we think in modules, and it’s a good thing. Adding and maintaining multiple scrip tags for dependencies? No more. You’ll start with SystemJS and then most likely will switch to Webpack.

5. Unit testing framework. Go with Jasmine.

6. Test runner that allows to run unit tests against multiple browsers from a command line. Use Karma runner.

7. Module bundler. You need to bundle your app into a small number of files so the browser won’t make several hundreds of network requests to load Angular modules. We use Webpack.

8. Task runner. Don’t even think of starting writing the app before setting up your build automation process. Start with using npm scripts. If you’ll run into any limitations, add some Gulp scripts.

9. Angular Router. This piece has been completely rewritten three times over the last year. It’s turning into a really powerful component.

10. Dependency Injection. Works really well and is stable.

11. Forms API. It’s still changing, but is getting there.

12. Inter-component communications. It’s important to architect your applications properly so components communicate in a loosely coupled way.

13. Reactive extensions RxJS. For async communications Angular 2 uses Observables and Subscribers instead of Promises.

14. The Http module. Responsible for communication with Http servers

15. Change detection (Zone.js). This piece monitors all async changes in your components and updates the view. For most apps you don’t need to worry about it, but if you’ll need to optimize the performance of your app, plan to invest some serious efforts to learn it.

16. UI components. Angular Material 2 is in its infancy with only 15 available components. If you need to deploy your app in prod this year, go with Wijmo 5 or PrimeNG

17. Angular CLI. This tool is in its infancy as well. It allows to quickly generate the project components and create the build. It starts with downloading the entire Internet to your computer and then generates stuff. My position is wait and see.

18. IDE. I saved this item for the happy ending. The IDEs used for TypeScript and Angular 2 are almost as good as their peers in Java or C# world. We use WebStorm, but Visual Studio Code is also great.

It took me a while to get comfortable with all the items from this list. I don’t know everything, but I know where to look for a solution. The Angular documentation is sparse and lots of APIs are not documented yet. There are multiple blogs that help with solving specific tasks, but most of the blogs become outdated because Angular 2 is still changing. In particular, the introduction of @NgModule in RC.5 forces me to refactor lots of code.

In the Summer of 2015 Angular 2 was in Alpha, the API was changing weekly, but I didn’t complain:  I was an early adopter. The problem is that it’s Summer of 2016, but as of Release Candidate 5 the API is still changing and I remain an early adopter.

This list may look intimidating, but if you’ll invest enough time the results will be rewarding. I believe in 2017 Angular will become the most popular framework for developing of the front end of the medium and large web apps.

If you’re interested in learning Angular 2 in depth, enroll into one of our workshops. We’ll run the next public training   online starting from September 11, 2016. I can also deliver this workshop privately for your organization (send an email to training@faratasystems.com).

Angular 2: Guarding routes

In this blog I’ll show you how to guard routes in Angular 2 Router.

Let’s consider some scenarios that require a certain validation to be performed to decide if the user (or a program) is allowed to navigate to or leave the route:

* Allow to open the route only if the user is authenticated and authorized to do so.

* Implement a multi-part form that consists of several components, and the user is allowed to navigate to the next form section only if the data entered in the current one is valid.

* Remind the user about the unsaved changes if he or she tries to navigate from the route.

The router has the hooks that give you more control over the navigation to/from a route, and you can use these hooks to implement the any of above scenarios to guard the routes.

Angular includes a number of component lifecycle hooks that allow you to handle important events in the life of a component. First, it worth noting that the route configuration is done outside of the components. You configure routes in an object of type RouterConfig, then give it to the provideRouter() function, which in turn is given to the function bootstrap() that loads your app.
The type RouterConfig is a collection of items that conforms to the Route interface shown below:

export interface Route {
 path?: string;
 pathMatch?: 'full' | 'prefix';
 component?: Type | string;
 redirectTo?: string;
 outlet?: string;
 canActivate?: any[];
 canDeactivate?: any[];
 data?: Data;
 resolve?: ResolveData;
 children?: Route[];
}

While configuring routes you’ll typically use two properties from this interface: path and component. For example, an app that has two links Home and Product Details can specify and bootstrap the routes as follows:

bootstrap(RootComponent, [
    provideRouter([
      {path: '',        component: HomeComponent},
      {path: 'product', component: ProductDetailComponent}]),
    {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

But in this blog I’d like to you to get familiar with the properties canActivate and canDeactivate that allow you to hook up the routes with the guards. Basically you need to write a function(s) implementing the validating logic that will return either true or false and assign it to one of these properties. If canActivate() of the guard returns true, the user can navigate to the route. If canDeactivate() returns true, the user can navigate from the route. Since both canActivate and canDeactivate properties of Route accept an array as a value, you can assign multiple functions (the guards) if you need to check more than one condition to allow or forbid the navigation.

Let’s create a simple app with Home and Product Details links to illustrate how you can protect the product route from the users who are not logged in. To keep the example simple, we won’t use an actual login service, but will generate the login status randomly.

We’ll create a guard class that implements the interface CanActivate, which declares only one function to implement: canActivate(). This function should contain the application logic that returns true or false. If the function returns false (the user is not logged in) the application will not navigate to the route and will print the error message on the console.

import {CanActivate} from "@angular/router";
import {Injectable} from "@angular/core";

@Injectable()
export class LoginGuard implements CanActivate{

  canActivate() {
      return this.checkIfLoggedIn();
  }

  private checkIfLoggedIn(): boolean{

      // A call to the actual login service would go here
      // For now we'll just randomly return true or false

      let loggedIn:boolean = Math.random() < 0.5;

      if(!loggedIn){
          console.log("LoginGuard: The user is not logged in and can't navigate product details");
      }

      return loggedIn;
  }
}

As you see from the code, my implementation of the function canActivate() will randomly return true or false emulating the user’s logged in status.

The next step is to update the router configuration so it uses our guard. The code snippet below shows how the function provideRouter() can look like for the app that has Home and Product Detail routes and the latter is protected by our LoginGuard:

provideRouter([
  {path: '',        component: HomeComponent},
  {path: 'product', component: ProductDetailComponent,
                    canActivate:[LoginGuard]}
])

Adding one or more guards to the array given to the canActivate property will automatically invoke all guards one after the other. If any of the guards returns false, the navigation to the route will be prohibited.

But who will instantiate the class LoginGuard? Angular will do it for us using its dependency injection mechanism, but you have to mention this class in the list of providers which are needed for injection to work. We’ll just add the name LoginGuard to the list of providers in the bootstrap() function of our app:

bootstrap(RootComponent, [
    provideRouter([
      {path: '',        component: HomeComponent},
      {path: 'product', component: ProductDetailComponent,
                        canActivate:[LoginGuard]}]),
    LoginGuard,
    {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

The complete code of the main app script is shown next:

import {bootstrap} from '@angular/platform-browser-dynamic';
import {Component} from '@angular/core';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';
import {provideRouter, ROUTER_DIRECTIVES} from '@angular/router';

import {HomeComponent} from './components/home';
import {ProductDetailComponent} from './components/product';

import {LoginGuard} from './guards/login.guard';

@Component({
    selector: 'basic-routing',
    directives: [ROUTER_DIRECTIVES],
    template: `
        <a [routerLink]="['/']">Home</a>
        <a [routerLink]="['/product']">Product Details</a>
        <router-outlet></router-outlet>
    `
})
class RootComponent {}

bootstrap(RootComponent, [
    provideRouter([
      {path: '',        component: HomeComponent},
      {path: 'product', component: ProductDetailComponent,
                        canActivate:[LoginGuard]}]),
    LoginGuard,
    {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

If you run this app and will try to lick on the Product Details link, it’ll either navigate to this route or print the error message on the browser console depending on the randomly generated value in the LoginGuard. The snapshot below was taken after the user tried to click on the Product Details link, but the LoginGuard “decided” that the user is not logged in.

ch3_loginguard

But if our unpredictable LoginGuard “decided” that the user is logged in, the screen will look as follows after clicking on the Product Details link:

nonguarded

Dependency Injection Benefit. Since a guard is injected into your app, you can use it as any other object. For example, you can inject it in your RootComponent:

 constructor (private _loginGuard:LoginGuard){}

Then invoke any methods defined on the guard class, e.g.:

 this._loginGuard.changeLoginStatus(true);

Our LoginGuard implements the method canActivate() without providing any arguments to it. But this method can be used with the following signature:

canActivate(destination: ActivatedRouteSnapshot,
            state: RouterStateSnapshot)

The values of the ActivatedRouteSnapshot and RouterStateSnapshot will be injected by Angular automatically and may become quite handy if you want to analyze the current state of the router. For example, if you’d like to know the name of the route the user tried to navigate to, this is how to do it:

canActivate(destination: ActivatedRouteSnapshot,
            state: RouterStateSnapshot) {

      console.log(destination.component.name);
   ...
}

Implementing the CanDeactivate interface that would control the process of navigating from a route works similarly. Just create a guard class that implements the method canDeactivate(), for example:

import {CanDeactivate, Router} from "@angular/router";
import {Injectable} from "@angular/core";
import {ProductDetailComponent} from "../product.component";

@Injectable()
export class UnsavedChangesGuard implements CanDeactivate<ProductDetailComponent>{

    constructor(private _router:Router){}

    canDeactivate(component: ProductDetailComponent){
      return window.confirm("You have unsaved changes. Still want to leave?");
    }
}

Don’t forget to add the canDeactivate property to the route configuration and inject the new guard in bootstrap(), e.g.:

bootstrap(RootComponent, [
    provideRouter([
      {path: '',        component: HomeComponent},
      {path: 'product', component: ProductDetailComponent,
          canActivate:[LoginGuard], canDeactivate:[UnsavedChangesGuard]}
    ]),
    LoginGuard, UnsavedChangesGuard,
    {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

For a fancier way of displaying confirmation dialogs use the MdDialog component from the Material Design 2 library (see https://github.com/angular/material2). This component will be released in the upcoming Alpha 8.

NOTE: If you want to delay the navigation to a route until certain data structures have been populated, use the property resolve from the Route interface. I’ll write a separate blog showing how to do it.

In this blog I didn’t show you the code of HomeComponent and ProductDetail component, but you can find them in the Github repo with the code samples from Chapter 3 from our book Angular 2 Development with TypeScript.

If you’re interested in learning Angular 2 in depth, enroll into one of our workshops. The next one we’ll run online starting from September 11, 2016.

Angular2, npm, and TypeScript: the first steps

Angular 2 is getting more and more stable. As of July of 2016 it reached the version Release Candidate 4 and I expect to see the official release of this framework not later than in October of this year.

While developing Angular 2 applications in TypeScript is easier than in JavaScript, the initial setup of the project may be intimidating. You need to be familiar with installing and configuring NPM packages and the process of transpiling of the code from TypeScript to JavaScript.

I’d like to offer you an extract from the video from the first session of our recent online training where I show how to install the TypeScript compiler, all required npm modules, and create configuration files for npm and the module loader SystemJS. In this video I was using Angular Release Candidate 1, but you can change the versions from rc.1 to rc.4 and everything will work fine.

Our next 6-week online workshop starts on September 11. It runs on weekends and will give you a solid understanding of how to work on the real-world project with Angular 2 and TypeScript.

If you’re reading this blog after September 11, check the schedule of our upcoming trainings at yakovfain.com.

What’s Happening in the JavaScript Ecosystem

Lots of things are happening there. As of today it’s the liveliest software ecosystem. The last time I’ve seen such an interesting gathering was 15 years ago in Java.

The Past

Fifteen years ago Java developers were looking down on the JavaScript folks. It was assumed that JavaScript was only good for highlighting menus and making an impression that the Web site is current by displaying a running clock on the page. Mobile phones still had buttons with one digits and three letters. There were no App stores. Java was promising “Write once run everywhere”, but now we can see that JavaScript actually delivered on this promise.

Say, you are developing in the XYZ language and wrote tons of programs in this language over the last 15 years. During this time new versions of the XYZ were released. The hardware advanced and new versions of operational systems came about. And you decided to take your old XYZ program written in the last century and run it on the brand new iPhone 6 or Android. Voila! It works without changing a line of code! I don’t know about the XYZ language, but programs written in JavaScript 15 years ago still work on iPhones.

js

Having said that, writing in JavaScript was never a pleasant experience. Some people made fun of JavaScript. Making fun of Brendan Eich, who created JavaScript in 10 days, was popular.

Other people started creating multiple libraries and frameworks to lower the pain of writing in plain JavaScript and making it work in different browsers. Ten years ago there were a couple of hundred JavaScript libraries and frameworks. People were overwhelmed by the freedom of choice well explained by Barry Schwartz in this video. The ECMAScript was abandoned. HTML5 was not born yet. In short, Web development was not fun.

The Present

In 2016 the situation is drastically different:

— The ECMAScript (ES) standard is actively being worked on, and its new versions will be released annually. Last year the ES6 (aka ES2015) spec was released and ES7 will be released this year. Now the JavaScript language has classes, lambda expressions (a.k.a. arrow functions), predictable “this”, block scope, generator functions, promises, destructuring, spread and rest operators and more. Some hardcore JavaScript developers immediately started WTF-ing classes as being a lot worse than functions, but these discussions are as useful as arguments about where to put curly braces in the if-statements: on the same or on the new line. Classes are just a syntax sugar that doesn’t change the prototypal inheritance, but reading and writing code is much easier now.

— All major browsers support most of the ES6 syntax.

— Transpilers easily generate ES5 program from the ES6 code so you can deploy the ES6 code today in all browsers.

— Dozens of languages emerged allowing you to write code that gets converted int to JavaScript automatically. The best of the breed is TypeScript created by Anders Hejlsberg from Microsoft. In the past he also created C#, Delphi and Turbo Pascal.

— Tons of open-source JavaScript code are published in various repositories. The most popular repo is npmjs.org, which has more than 200K libraries, frameworks and useful utilities. By the way, npm literally killed bower, his former competitor.

— Google created a super-fast JavaScript engine V8. The Node.js framework allows you to write standalone applications that don’t require browsers. Node servers started to compete with the ones written in Java. Despite the single-threaded architecture of I/O, Node’s asynchronous processing allows handling tens of thousands client requests simultaneously.

— There are build automation tools (we use Webpack), which minimize and optimize the JavaScript code with the further bundling separate files together so browsers don’t need to make dozens of requests to the server to download that home page.

— The WebComponents standard prescribes how to develop custom HTML components. The Material Design principles explain how to develop nice-looking Web pages. Google implemented these principles in a library of custom components called Polymer. We already tried it in the real-world projects, and it works!

– HTTP/2, a major revision of HTTP will substantially speed up the client-server communications.

Libraries and Frameworks

The number of JavaScript libraries and frameworks is comparable to the number of presidential candidates in the Republican Party in the USA. Those (mainly enterprise) folks who want to get everything out of the box and are not afraid to sell themselves into slavery still use Ext JS. This is not an easy to master framework, but it has everything you need to develop back-office enterprise applications.

Developers who want a lighter framework that puts a structure on your app with navigation and data binding usually go with AngularJS 1.x or Ember. They would need to integrate third-party libraries for graphical components, grids, and a usual Twitter’s Bootstrap (to make the app usable on mobile phones and tablets), but it’s doable. Some people prefer the React framework from Facebook, but React is mainly about views, and you’d need to use some third-party libraries to build an app.

Those who don’t like prix fixe meals and prefer a la carte menus pick a bunch of small libraries each of which can do one thing well. They are ready to face the issues while trying to make these libraries work together. Such people charge higher rates and project managers keep their fingers crossed hoping that these developers won’t quit.

Fashion Trends

In this season every top model-developer entering a catwalk wears reactive accessories. Not that “reactive” is something completely new (even our grandmas liked messaging, pub-sub, and the observer-observable pattern), but in today’s asynchronous UI world, reactive is a must have. We need to give a credit to Microsoft (do people still hate it by default?) for beautifully designed reactive extensions, which in JavaScript world go by the name RxJS.

In the reactive world every component or service is implemented as a stream. Everything is a stream. You are a stream. I am a stream. A click on a button spits out the event as a next element of a stream. An HTTP request to a server returns a response as an element of a stream (promises had their 15-min of fame and are considered old fashioned these days). A piece of data pushed over a WebSocket connection is an element of a stream you can subscribe to. And there is a nice little twist to it: a subscriber can regulate the stream volume and lower the pressure if need be.

A year ago a team from Google decided to re-write their super-popular (1.1M devs) framework AngularJS. They started with creating a new language AtScript just for the new Anguar 2, but then invited the TypeScript team from Microsoft (can we start liking Microsoft, just a little bit?), and asked them to add some features to the TypeScript language. Microsoft folks kindly agreed, and Google wrote Angular 2 in TypeScript, which also became a recommended language for developing Angular 2 apps. Now the code of Angular 2 apps is easy to read and write even for Java and C# developers (see this). Needless to say that RxJS is embedded inside Angular 2.

Jokes aside, I really like the Angular 2/TypeScript/RxJS/npm/Webpack combo. During the last ten months I’ve been working with my colleague Anton Moiseev on the book “Angular 2 Development with TypeScript“. So far Manning published 300 pages of this book, and the remaining 150 pages are almost ready. The code faindz will lower the price of the eBook by 39%.

If you prefer to learn Angular 2 in a classroom setting, this year I’ll be teaching Angular 2 classes and my training/speaking schedule is published here.

The Bottom Line

My hat off to Brendan Eich for not over-engineering the language. JavaScript is getting a lot of traction and the demand for professional JavaScript developers will grow by leaps and bounds. Be there and stay current.

Why Java Developers Will Embrace Angular 2 and TypeScript

Most of the Java developers I know don’t like JavaScript. Initially. They would give you different reasons why, but the real one is simple: too much to learn to make it work. For many Java developers creating the front end of a Web application in JavaScript is a chore to write and a burden to maintain. Nevertheless JavaScript rules in Web development and the new version of JavaScript (ES6) will make it even more popular.

ES6 offers classes, standardized module definition, arrow expressions (lambdas), predictable “this” and a lot more. Firefox and Chrome already support most of the ES6 syntax, and other browsers are getting there as well.

But there is something better than ES6: the TypeScript language, which has most of what ES6 has to offer plus types, casting, interfaces, generics, and annotations. The TypeScript code analyzer will help you to see syntax errors even before you run the program. Code refactoring works as well. In this blog I stated the main reasons of why TypeScript is the right tool for JavaScript development.

Now let’s take a quick glance at Angular 2, a complete re-write of the popular open-source framework managed by Google. There were two Beta releases of Angular 2, and it’s safe to start using it for your next Web project unless your app has to go to prod in the first half of 2016. Angular 2 is stable enough for serious development, and I know this first hand after surviving a couple of dozens of alpha releases of Angular 2.

Disclaimer. You can write Angular applications in the current JavaScript (ES5), next JavaScript (ES6), Dart, or TypeScript. Based on my experience with all these languages using TypeScript is the best option.

What makes the Angular 2/TypeScript combo so appealing to Java folks?

First of all, the code looks clean and easy to understand. Let’s do an experiment. I’ll give you a two-paragraph intro on how to write an Angular component in TypeScript followed by the sample code. See if you can understand this code.

Any Angular application is a hierarchy of components represented by annotated classes. The annotation @Component contains the property template that declares an HTML fragment to render by the browser. The HTML piece may include the data binding expressions, which can be represented by double curly braces. If a view depends on other components, the @Component annotation has to list them in the property directives. The references to the event handlers are placed in the HTML from the @Component section and are implemented as the class methods.

The annotation @Component also contains a selector declaring the name of the custom tag to be used in HTML document. When Angular sees an HTML element with the name matching a selector, it knows which component implements it. The lesson is over.

Below is a code sample of a SearchComponent, and we can include it in an HTML document as <search-product> because its declaration includes the selector property with the same name.

@Component({
  selector: 'search-product',
  template:
     `<div>
          <input #prod>
          <button (click)="findProduct(prod.value)">Find Product</button>
          Product name: {{product.name}}
        </div>
    `
})
class SearchComponent {
 
   product: Product; // code of the Product class is omitted

   findProduct(prodName: string){
    // Implementation of the click handler goes here
   }
   // Other code can go here
}

A Java developer can read and understand most of this code right away. OK,ok. I’ll give you more explanations. The annotated class SearchComponent declares a variable product, which may represent an object with multiple properties, one of which (name) is bound to the view ({{product.name}}). The #prod is a local template variable that stores a reference to the input field so you don’t need to query DOM to get the entered value.The (click) notation represents a click event, and the event handler function gets the argument value from the input field.

Note that the HTML template is surrounded with the back tick symbols, which allow you to write the markup in multiple lines in a readable form. If you prefer to store HTML in a separate file instead of template use the templateURL property:

templateUrl: './search.html' 

Dependency Injection. Angular architecture will be very familiar to those who use Spring framework or Java EE. Angular comes with the Dependency Injection (DI) module, which instantiates an object using a registered class or a factory and injects it to the application component via constructor’s arguments. The following code will instruct Angular to instantiate the class ProductService and inject it into the ProductComponent:

@Component({
   providers: [ProductService]
})
class ProductComponent {
product: Product;
 
  constructor(private productService: ProductService) {
 
     this.product = this.productService.getProduct();
  }
}

Specifying the provider and declaring the constructor with the type is all you need for injecting the object. Application components form a hierarchy, and each component may have its own injector. Injectors are not singletons.

App structure. The following image shows what the main page of a sample application is made up of. The parent component includes child components, which are surrounded with green borders.

ch2_auction_home_page_components

Router. Angular shines in development of single-page applications (SPA), where the entire Web page is never reloaded. Angular router allows you to easily configure the page fragments (the views) that should be loaded based on the user’s actions. The code snippet below includes the annotation @RouteConfig that configures two routes Home and ProductDetail, which are mapped to the corresponding components (HomeComponent and ProductDetailComponent). The user navigates the application by clicking on the links with the corresponding routerLink attribute, which will display the requested component in the area marked as <router-outlet>.

@Component({
    selector: 'basic-routing',
    template: `<a [routerLink]="['/Home']">Home</a>
              <a [routerLink]="['/ProductDetail']">Product Details</a>
              <router-outlet></router-outlet>`,
    directives: [ ROUTER_DIRECTIVES]
})

@RouteConfig([
    {path: '/',        component: HomeComponent, as: 'Home'},
    {path: '/product', component: ProductDetailComponent, as: 'ProductDetail'}
])
class RootComponent{
}

Inter-component communication. Each component in Angular is well encapsulated, and you can create it in a losely-coupled manner. To pass the data from the outside world to the component just annotate a class variable(s) with @Input() and bind some value to it from the parent component.

class OrderComponent {

    @Input() stockSymbol: string; 
    @Input() quantity: number; 
}

To pass the data from the component to the outside world, use the @Output annotation and dispatch events through this variable. Dispatch to whom? Ain’t none of the component’s business. Let’s whoever is interested listen to this event, which can be either a standard or a custom event carrying a payload.

class PriceQuoterComponent {
    @Output() lastPrice: EventEmitter<IPriceQuote>  = new EventEmitter(); 
 ...
    this.lastPrice.emit(priceQuote)
 }   

See something familiar? You got it. That thingy in the angle brackets after EventEmitter denotes a generic type, and IPriceQuote can be an interface. TypeScript supports generic and interfaces.

Casting. TypeScript supports types, classes, and interfaces (class A extends B implements D, E, F). It support type casting as well. As in Java, upcasting doesn’t require special notation. To denote downcasting surround the target type with angle brackets and place it before more general type as shown in the screenshot below.

casting

I took this screenshot after placing the cursor before value in line 17. I use WebStorm 12 IDE (a little brother of IntelliJ IDEA), which supports TypeScript quite nicely (including refactoring), and this supports improves with every minor release of WebStorm. If I wouldn’t declare the variable with the type in line 15 and wouldn’t use casting, the code would still work, but the IDE would show value in red and the code completion wouldn’t work in line 17.

Streams and lambdas. These are big in Java 8. Angular 2 incorporates RxJS, the library with react extensions, where streams is a religion. Everything is a stream in RxJS, and Angular 2 promotes using observable streams and subscribers.
Even events are streams, can you believe this? The user types in an HTML input field or is dragging the mouse, which generates a stream that you can subscribe to (think observer/observable or pub/sub).

Make an HTTP request or open a WebSocket and subscribe to the observable stream, which is a Promise on steroids. Handling results is still an asynchronous operation, but as opposed to a Promise it can be cancelled.

In Java 8 you can run a stream through a number of changed intermediate operations (e.g. map()) followed by a terminal one. In Angular 2 you can do the same:

class AppComponent {

  products: Array = [];

  constructor(private http: Http) { 

    this.http.get('/products') 
        .map(res => res.json()) 
        .subscribe(
            data => {
              if (Array.isArray(data)){
                this.products=data; 
              } else{
                this.products.push(data);
              }
            },
            err =>
              console.log("Can't get products. Error code: %s, URL: %s ",  err.status, err.url), 
            () => console.log('Product(s) are retrieved') 
        );
  }
}

If the above code requires explanations, then your Java is a little rusty. Seriously.

Module loading. One of the important features that ES6 brings to Web development is standardization of modules. The application code consists of modules (typically one module is one script file). Using the export keyword (e.g. export class Product {...}) you specify which members of the module should be exposed to other scripts. Accordingly, a script can include one or more import statements to have access to other modules.

ES6 includes the syntax for importing/exporting modules, but the standardization of the module loader System is postponed, and we use the polyfill SystemJS that can load modules of all existing formats (including ES6). When the System object will become standard in all browsers that support ES6, you won’t need to change your code (removing the polyfill is all that’s needed).

The main HTML file of he Angular/TypeScript application simply includes the configuration of the loader and transpiler (the running code must be compiled to JavaScript) and import statement of the main application component:

<body>
  <app>Loading...</app>

  <script>
    System.config({
      transpiler: 'typescript',
      typescriptOptions: {emitDecoratorMetadata: true},
      packages: {app: {defaultExtension: 'ts'}}
    });
    System.import('app');
  </script>
</body>

In the above code snippet the System object imports the module from the file app.ts, which is a root component of the application and may have child components represented by custom HTML tags. The System loader reads all import statements in each application component and loads all dependencies accordingly. Lazy loading of the modules is supported as well.

Deployment. Java developers use build tools like Maven or Gradle for deployment. Guess what, Angular developers use them as well. The TypeScript code needs to be transpiled into JavaScript, minimized and obfuscated before deployment to QA or prod servers. Some people use Grunt, some Gulp, but we use Webpack for bundling the code and npm scripts for deployment. The jury is still out on the best build automation tools, and we keep our eyes open.

I hope that after reading this blog thousands (ok, hundreds) of Java developers will want to take a closer look at Angular 2. Start with Angular architecture.

In this blog I showed you just a tip of the iceberg. You’d need to invest some time in learning Angular 2 and TypeScript, but the learning process isn’t too steep for the Java folks. If you want to make this process as pleasant as it can be, get the book that I’m co-authoring or enroll in one of our training classes.

IMHO Angular 2 will make as big of an impact in the JavaScript community as Spring Framework has in the Java world.

One more thing… View rendering is implemented in a separate tier, which means that it doesn’t have to be HTML only. You will be able to implement mobile applications that will use native iOS or Android UI components. The folks from Telerik are working with the Angular team to integrate this framework with NativeScript (read this).

Setting up the Environment for Node.js and TypeScript

Currently I’m working on the book chapter explaining how Angular 2 communicates with the servers. An easy approach would be to use for the data feed a public RESTful API of one of servers (Youtube or something), but I wanted to have my own locally installed server.

Using one of the Java servers would be an easiest choice for me, but this would limit the readership to only those who know Java. Can’t do. Let’s stick to JavaScript. Opps, I meant to say TypeScript. Actually what I really meant was using Node.js on the server with the TypeScript.

Disclaimer: I’ve been using Node as a runtime for a while, but I’m very new to developing with Node.js framework.

After this disclaimer about 50% of the readers should have abandoned this page. Since you’re not one of them, let’s learn together how to start using the Node framework with TypeScript.


Creating a Web Server with Node and TypeScript

Node.js (a.k.a. Node) allows you to create standalone applications in JavaScript. Node does a great job in the area of communications using HTTP or WebSockets, so let’s start with creating a simple Web server.

I assume that you already have both Node and TypeScript compiler installed on your computer, otherwise do it now.

We’ll start with creating a standalone Node application implementing the server-side tier of our mini project. In this blog we’re no going to write the Angular client, but if we would our project’s directory could have the following structure:

ch8_project_structure

To stay IDE-agnostic lets open a command prompt and create a directory named http_sample with the subdirectory server and configure a new Node project there by running the following command:

npm init -y

This will create a small npm configuration file package.json with default settings. Now let’s create a file hello_server.ts with the following content:

import * as http from 'http'; // 1

const server = http.createServer((request, response)=> {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World!\n');
});

const port = 8000;

server.listen(port); // 2
console.log('Listening on http://localhost:' + port);

1. This code loads the Node’s module using the ES6 syntax “import * as” supported by TypeScript as well. Note that we use const instead of var here.

2. The listen() function is what makes this program run infinitely. Every client’s request will get a response with HTTP code 200 and the text Hello World!

The above code need to be transpiled and we’ll create the file tsconfig.json in the project directory to configure the tsc compiler:

{
 "version": "1.7.5",
 "compilerOptions": {
 "target": "es5",
 "module": "commonjs", // 1
 "emitDecoratorMetadata": true,
 "experimentalDecorators": true,
 "outDir": "build" // 2
},
"exclude": [
   "node_modules", // 3
   "client" // 4
 ]
}

1. This will instruct the TypeScript compiler tsc to transpile modules according to the CommonJS spec. In our example the transpiler will convert the import statement

import * as http from 'http';

into this:

var http = require('http');

2. The transpiler will put the .js files into the directory build

3. Don’t transpile code located in the directory node_modules that contains the project dependencies

4. When you create the directory client for the Angular (or other) app, but we don’t want to transpile the client’s code because the SystemJS loader will do it on the fly.

NOTE: If you decide to copy the content of tsconfig from the listing above, remove the comments as they are not supported in JSON format. I used them here only to provide the code notes with explanations.

After running the tsc command the transpiled file hello_server.js will be saved in the build directory and we can start our Web server:

node build/hello_server.js

Node start the JavaScript engine V8, which in turn will run the script from hello-server.js, which creates a Web server and prints a message “Listening on http://localhost: 8000”. Open your browser at this URL, and you’ll see a Web page with the text Hello World!

NOTE: In your IDE, to get context-sensitive help and the compile-type error check, install the type definition file for Node using the TypeScript Definition Manager tsd (install it first) by running the command tsd install node, which will create the directory typings in your project that will contain the file node.d.ts. In this blog I still use tsd, but it’s in a process of being deprecated in favor of another tool called Typings.

Creating a Web Server to Serve JSON Data

Now let’s teach our Node Web server to serve JSON data. To send JSON to the browser you need to modify the header to specify the MIME type to be application/json. The following code snippet shows what it takes to send a JSON object:

const server = http.createServer((request, response) => {
response.writeHead(200, {'Content-Type': 'application/json'});
response.end('{"message": "Hello Json!"}\n');});

While the above code sample suffices as an illustration of how to send a JSON data, real world applications require more functionality on the server side, e.g. reading files, routing based on the provided path, handling various HTTP requests based on the method (GET, POST et al). For our auction example we’ll need to respond with either products or reviews data based on the request.

To minimize manual coding we’ll install Express, which is a Node framework. I won’t be using all of the functionality of Express for a simple reason: I don’t know Express. Actually, I should have said, “I’m not an Express expert”, but let’s be honest here. Express will help with creating a RESTful Web service that will send the appropriate JSON file based on the client’s request.

To install Express we’ll run the following command from the project directory:

npm install express –save

This will download Express into the node_modules folder of our project and will update the dependencies section in package.json. To install Express type definition files in the typings directory run the following command:

tsd install express

Now we can import Express into our application and start using its API. Let’s assume that we want to create a couple of endpoints to serve the product information and reviews. Below is the code of the file my-express-server.ts that shows how you can implement routing based on the URL for the HTTP method GET:

import * as express from 'express';
const app = express(); // 1

app.get('/', (req, res) => res.send('Hello from Express')); // 2
.
app.get('/products', (req, res) => res.send('Got a request for products')); // 2

app.get('/reviews', (req, res) => res.send('Got a request for reviews')); // 2

const server = app.listen(8000, "localhost", () => { // 3

   const {address, port} = server.address(); // 4
   console.log('Listening on http://localhost:' + port);
});

1. Create an object that denotes the Express application.

2. In the above example we’ve illustrated routing only for the GET requests using the method get(), but Express supports all methods required for handling HTTP requests and responses. You can find the declarations (with types) of all of them in the file express.d.ts.

3. Start listening on the port 8000 at the address localhost and execute the code provided in the fat arrow function.

4. We use the destructuring syntax to automatically extract the values of the properties address and port. In the ES5 syntax we’d need to write two lines instead of one:

var address = server.address().address;
var port = server.address().port;

If you transpile the code and start this server (node my-express-server.js), you’ll be able to request either products or services depending on which URL you enter as shown below.

ch8_express_routing

Live TypeScript Recompilation and Code Reload

Since we write our examples in TypeScript, we need to use tsc to transpile and deploy JavaScript in Node. The TypeScript compiler has the compilation option -w that runs tsc in the watch mode so whenever a TypeScript file changes it gets recompiled automatically. To set the auto-compilation mode for our code we’ll open a separate command window in the directory with the sources and run the following command:
tsc -w

When no files to compiled are specified, tsc will get the options for compilation from the file tsconfig.json. Now whenever you make a change in the TypeScript code and save the file it’ll generate the corresponding .js file. Accordingly, to start our Web server with Node you can use the following command:
node my-express-server.js

Live recompilation of the TypeScript code helps, but the Node server won’t automatically pick up code changes after it started. You’d need to manually restart the Node server to see your code changes in action unless you’ll use a handy utility Nodemon  that will monitor for any changes in your source and automatically restart your server and reload the code.

You can install Nodemon either globally or locally. For global install using the following command:
npm install -g nodemon

The following command will start our server in a monitoring mode:
nodemon my-express-server.js

If you want to get fancy, install Nodemon locally (npm install nodemon –save-dev) and introduce npm scripts in your package.json file:

 “scripts": {
 "start": "node my-express-server.js",
 "dev": "nodemon my-express-server.js"
 },
 "devDependencies": {
 "nodemon": "^1.8.1"
 }

Now you’ll be starting the server as npm run dev in the development mode (auto restart/reload) or npm start in production (no restart/reload).

Injecting a Service in Angular 2

This is a sequel to my blog “Getting Familiar with Angular 2 DI“. This time we’ll create a simple application that will use a ProductComponent to render product details and ProductService to supply the data about the product. In this blog I use Angular 2 Beta.0. The working application is deployed as a plunk and it’ll produce the page shown below.

ch4_running_di_sample

The ProductComponent can request the injection of the ProductService object by declaring the constructor argument with a type:

constructor(productService: ProductService)

The following image will give you a better idea how these component and service are related.

ch4_di_product2

The file index.html will host a root component of your app’s main page, which in turn will include ProductComponent that’s dependent on ProductService.

Note the import and export statements. The class definition of the ProductService starts with the export statement to enable other components to access its content. Accordingly, the ProductComponent includes the import statement providing the name of the class (ProductService) and the module being imported (located in the file product-service.ts).

The providers statement instructs Angular to provide an instance of the class ProductService when requested.

The ProductService may communicate with some server requesting details for the product selected on the Web page, but we’ll skip this part for now and will concentrate on how this service can be injected into ProductComponent.

Our app will consist of the following files:

* The file index.html that loads the code of the app.ts that renders root component, which uses ProductComponent
* The ProductComponent will be implemented in the file product.ts.
* The ProductService will be implemented in a file product-service.ts.

The file index.html performs three functions:

* Loads Angular and its dependencies
* Hosts a root component represented by the tag .
* Configures SystemJS and uses it to load the application component from app.ts.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Angular DI Sample</title>
  
  <script src="https://npmcdn.com/angular2@2.0.0-beta.0/bundles/angular2-polyfills.js"></script>
  <script src="https://npmcdn.com/typescript@1.7.5/lib/typescript.js"></script>
  <script src="https://npmcdn.com/systemjs@0.19.8/dist/system.src.js"></script>
  <script src="https://npmcdn.com/rxjs@5.0.0-beta.0/bundles/Rx.js"></script>
  <script src="https://npmcdn.com/angular2@2.0.0-beta.0/bundles/angular2.dev.js"></script>
  
  <script>
    System.config({
      transpiler: 'typescript',
      typescriptOptions: {emitDecoratorMetadata: true},
      packages: {app: {defaultExtension: 'ts'}}
    });
  </script>
</head>
<body>
  <disample-root>Loading...</disample-root>
  <script>System.import('app/app');</script>
</body>
</html>

The AppComponent is shown next. It hosts the ProductComponent, hence it needs to import and declare it in the property directives. Note that the name of the selector of the AppComponent is disample-root, and we used it in index.html above:

import {bootstrap} from 'angular2/platform/browser';
import {Component} from 'angular2/core';
import ProductComponent from './components/product';

@Component({selector: 'disample-root',
  template: `<h1> Basic Dependency Injection Sample</h1>
             <di-product-page></di-product-page>`,
  directives: [ProductComponent]
})
class AppComponent {}

bootstrap(AppComponent);

Based on the tag it’s easy to guess that there is a child component with the selector having this value. This selector is declared in ProductComponent, which will get its dependency (ProductService) injected via the constructor:

import {Component, bind} from 'angular2/core';
import {ProductService, Product} from "../services/product-service";

@Component({
  selector: 'di-product-page',
  template: `<div>
  <h1>Product Details</h1>
  <h2>Title: {{product.title}}</h2>
  <h2>Description: {{product.description}}</h2>
  <h2>Price: \${{product.price}}</h2>
</div>`,
  providers:[ProductService] // 1
})

export default class ProductComponent {
  product: Product;

  constructor( productService: ProductService) { // 2

    this.product = productService.getProduct();
  }
}

1. The providers property maps a token that we’ll use in the code to the name of the class that will represent this token. In this example the name of the token is the same as the name of the class: ProductService, so we use a short notation without invoking the function provide() with useClass.

2. Injection of the ProductService will be done here, and Angular will instantiate this object.

We separate the type ProductService from the actual implementation of this service being that a class ProductService, OtherProductService or something else. Replacing one implementation with another comes down to changing the providers line.

The constructor of ProductComponent invokes getProduct() on the service and places a reference to the returned Product object into the class variable product, which is used in the HTML template.

Using double curly braces the above markup allows us to bind the properties title, description, and price of the class Product. The file product-service.ts includes the declaration of two classes: Product and ProductService.

export class Product {  // 1
  constructor(
    public id: number,
    public title: string,
    public price: number,
    public description: string) {
  }
}

export class ProductService { 

  getProduct(): Product { // 2
    return new Product(0, "iPhone 7", 249.99, "The latest iPhone, 7-inch screen");
  }
}

1. The class Product represents a product (a.k.a. Value Object). This type will be used outside of this script so we export it.

2. For simplicity the method getProduct() always returns the same product with hard-coded values. In the real-world applications you’d need to get it from some external data source, e.g. by making an HTTP request to a remote server.

To see this example in action open this plunk and press the button Run.

The instance of ProductService was injected into ProductComponent, and the product component rendered product details provided by the server.

In the next section you’ll see a ProductService decorated with the @Injectable annotation, which is used for generating DI metadata in cases when the service itself uses DI as shown in the next section. It’s not needed here because this service doesn’t get any other service injected into it.

Injecting an Http Service

Pretty often a service would need to make an HTTP request to get the requested data. The ProductComponent depends on ProductService which will be injected using Angular DI mechanism. If the ProductService needs to make an HTTP request, it’ll have an Http object as its own dependency. The ProductService will need to import the Http object from Angular, and should have a constructor for injecting Http object. The following diagram shows that ProductComponent depends on ProductService, which has its own dependency: Http.

ch4_dependency_dependency

The following code snippet illustrates the Http object injection into ProductService and retrieval of products from the file products.json:

import {Http} from 'angular2/http';
import {ProductService} from "./product-service";

@Injectable
export class ProductService {
    constructor(private http:Http){
      let products = http.get('products.json');
    }
   // other app code goes here
   // will write a separate blog about using Http
}

The class constructor is the injection point, and we need to add the provider of object of the Http type. Angular offers a special object HTTP_PROVIDERS, which provides injectables for making HTTP requests and could be specified as an application-level dependency during the bootstrap. The application-level providers are available for all application components. The ProductComponent would need to explicitly specify the HTTP providers:

import {HTTP_PROVIDERS} from 'angular2/http';

class ProductComponent {

  constructor(private productService: ProductService) {}
  
  // The rest of the code goes here 
}
bootstrap(ProductComponent, [HTTP_PROVIDERS]);

Leaky Abstraction Detected. You need to specify the HTTP provider at the component level despite the fact that Http is used only inside the service (ProductComponent <-ProductService <- Http). This breaks encapsulation of the ProductService. In other words, the ProductService abstraction leaks. Imagine that ProductService is used in 10 different components, and for some reason we decided to update ProductService replacing HTTP with another way of getting product information. This would require code modification not only inside the ProductService, but also in those 10 components.

I'd like to keep the declaration of HTTP provider inside the ProductService, but currently it’s not possible. I raised this question at Angular’s repo, and you can join the discussion here

.

In one of the future blogs I'll show you how easy it is to replace one implementation of the service with another using Angular DI.

Stay tuned for more Angular 2 blogs. My other Angular-related blogs are here. Manning is publishing the drafts of our book “Angular 2 Development with TypeScript“. Starting on February 28, we’ll also teach an online class on Angular 2.