TypeScript: callable interfaces

TypeScript is a superset of JavaScript and over the last year it’s gaining popularity by leaps and bounds. Angular 2 and RxJS 5 are written in Typescript. I believe about a million of developers are using TypeScript today for app development (this is not official stats). I’m using TypeScript for more than a year and it’s so much more productive than JavaScript! For me (a Java developer), TypeScript makes a lot more sense than JavaScript. But if your main language was JavaScript, some of the TypeScript’s concepts might look foreign for you. I’m planning to write a couple of blogs illustrating TypeScript syntax.

Web browsers don’t understand TypeScript and there’re no plans to change this any time soon. So if you’ll write a program in TypeScript, it has to by transpiled (think compiled) into JavaScript first. I’m not going to discuss the TypeScript compiler here, but will be using the Playground, where you can write code fragments in TypeScript, and they’ll be immediately transpiled into JavaScript (it’s going to be the ECMAScript 5 version).

TypeScript supports different flavors of interfaces. Today we’ll get familiar with a callable interface that contains a bare function signature (a signature without a function name). I’ll show you the syntax first and then will explain how a callable interfaces are useful. The following example shows a bare function signature that takes one parameter of type number and returns a boolean.

(percent: number): boolean;

The bare function signature indicates that when this function will be implemented it’s going to be callable. So what’s the big deal? Let’s consider an example that declares IPayable interface, which will contain a bare function signature. In our company work employees and contractors that will be represented by a class Person. The rules for increasing pay of employees and contractors are different, and I’ll create separate functions that implement these rules. These functions will be passed as arguments to the constructor of the class Person and will be invoked inside the constructor of the Person instances.

interface IPayable { // <1>
    (percent: number): boolean;
}

class Person  {
    constructor(private validator: IPayable) { // <2>
    }

    increasePay(percent: number): boolean { // <3>
        return this.validator(percent);
    }
}

let forEmployees: IPayable = (percent) => { // <4>
        console.log("Increasing salary by ", percent);
        return true;
    };

let forContractors: IPayable = (percent) => { // <5>
    var increaseCap: number = 20;

    if (percent < increaseCap) {
      console.log("Increasing hourly rate by", percent);
      return true;
    } else {
      console.log("Sorry, the increase cap for contractors is ",
                                         increaseCap);
      return false;
    }
}

let workers: Array<Person> = [];

workers[0] = new Person(forEmployees); // <6>
workers[1] = new Person(forContractors);

workers.forEach(worker =>worker.increasePay(30)); // <7>

1. A callable interface that include a bare function signature.

2. We declare that the constructor of the Person class takes an implementation of the callable interface IPayable as an argument.

3. The increasePay() method invokes the bare function on the passed implementation of IPayable, supplying the pay increase value for validation.

4. The rules for salary increases for employees are implemented using the arrow function expression.

5. The rules for pay increases for contractors are implemented using the arrow function expression.

6. Instantiates two Person objects, passing different rules for pay increases.

7. Invokes increasePay() on each instance, validating the 30% pay increase.

First I’ll enter the above code in the TypeScript playground on the left, and the generated JavaScript code will be shown on the right (see http://bit.ly/2hUdsGn). Read the JavaScript code – it should help you understanding what’s going on. Note, that there are no traces of our IPayable interface on the right since JavaScript doesn’t support interfaces.

play

If you click on the button Run and open the browser’s console you’ll see the following output:

Increasing salary by 30
Sorry, the increase cap for contractors is 20

Cool. But in JavaScript you can also pass a function as an argument to a higher order function (constructor in our case), right?

Now imagine that you’re supposed to pass a function with a certain signature to a higher order function, but made a mistake and passed a wrong function. This will result in a runtime error.

Callable interfaces allow you to to catch this mistake during the development stage. For that we declare the signature of a function that has to be passed to the constructor of the instance of the Person object.

Now purposely introduce an error – declare a function with the wrong signature (do it on the left side at the playground):

let forTempWorkers = () => 
      console.log("Can't increase salary for temps"); 

Try to pass it to the constructor to a Person:

workers[0] = new Person(forTempWorkers); 

TypeScript will immediately highlight the above line as erroneous, and you’ll catch this error during dev time whereas in JavaScript this error would silently sneak into your code causing the app to blow up during the runtime.

play2

So callable interfaces are your friends, aren’t they?

Angular 2: What’s with the name?

The Angular 2 framework now supports semantic versioning, and it was announced that major upgrades (with breaking changes) will be released twice a year. In particular, in March of 2017 the version 4.0.0 will be released, in September – 5.0.0 and so on.

This is all good but the problem is that not only the versioning will be different, but Angular team is considering changing the name from Angular 2 to Angular. This will create lots of confusion in the Angular community.

First, a bit of history. The older version of this super popular Web framework is called AngularJS (currently at 1.6.0). Two years ago a complete redesign of this framework was announced, and the new framework got the name Angular 2. I guess, someone at Google suggested to keep the word Angular in the name to leverage the fact that more than 1.3 million of software developers were already using AngularJS, and most of these people would want to upgrade to the newer version of the same framework.

The problem is that Angular 2 is completely different framework, and suggesting the roadmap for upgrading existing AngularJS apps to Angular 2 is no different than suggesting a roadmap for upgrading an app from Ember or React to Angular 2. But the marketing plan worked out nicely, and more than 700K developers are using Angular 2 by now. No wonder – Angular 2 is a great framework.

People started creating Angular 2 communities to post articles, and ask for help. For example, the Reddit’s Angular 2 community is pretty active and has 6800 members: https://www.reddit.com/r/Angular2/. Questions and answers on StackOverflow are marked with the tag #angular2: http://stackoverflow.com/questions/tagged/angular2. LinkedIn has a group of 7900 Angular 2 developers: https://www.linkedin.com/groups/8434339.

Bloggers (myself included) are posting articles and tutorials that have Angular 2 in their names. PluralSight, Lynda.com, egghead.io and many independent developers produce video contend with Angular 2 in their titles.

Book authors (myself included) wrote about a dozen books with Angular 2 in their titles, and these books will remain relevant and useful for several years, unless Google will decide to completely re-write this framework again.

If the framework will be renamed to Angular, anyone searching for Angular 2 content will be inevitable getting materials for both AngularJS and Angular 2. Just try finding posts on StackOverflow tagged as Angular: http://stackoverflow.com/questions/tagged/angular. The “angular” in the URL will be automatically converted to “angularjs” and you’ll be seeing 200K+ irrelevant posts about AngularJS. IMO, it’s a disservice to the community. BTW, there is Angular Reddit group as well: https://www.reddit.com/r/angular, and these developers may want to keep their forum clean from Angular 2 posts.

I suggest to keep Angular 2 as the name of the framework. The digit 2 here won’t represent the version, but rather the next generation of this framework. So in March we’ll get Angular 2 v. 4.0.0, in September – Angular 2 v.5.0.0 and so on. Content producers can still include “Angular 2” in the titles and use the tag #angular2 in social networks.

What do you think?

P.S. The community may decide to keep using the tag #angular2 regardless of the official name of this framework.

A Web developer’s reading list

Manning is planning to release a free book sampler that would include chapters from different books covering modern Web development process. They asked me to select books/chapters and write a short intro, which I did and decided to share this with you.

The modern world of Web development requires software engineers who are well versed in multiple disciplines. Of course, familiarity with the JavaScript syntax is a must. As Atwood’s law states, “Any application that can be written in JavaScript, will eventually be written in JavaScript”. Well, maybe not in the pure JavaScript, but in its more productive superset called TypeScript.

Web developers use frameworks and/or libraries to avoid re-inventing the wheel while working on applications. While many people are still happy with jQuery, more progressive developers are debating: Angular or React? This comparison is wrong because React is a library while Angular is a framework with batteries included. But Angular and React are the most popular tools in the Web development ecosystem today.

There is a trend to develop applications using principles of reactive programming. The data consumer subscribes to the data stream that’s pushed to the consumer only when the data is available. This is an alternative to the polling model that requires the client to make periodic requests for data, which may or may not not be available. The RxJS library implements the push model via observable streams of data. This library offers you a variety of chainable operators (functions) that handle and transform the data en route.

Making your application available on mobile devices is important. Will your Web application look good on a small screen or you’d better create separate native applications for each mobile platform? There is is a third approach to create so called hybrid applications that run a Web container inside your mobile device translating HTML elements into their native counterparts. Actually there is a forth approach that suggests reusing the most of the code base of your Web app while compiling the UI portion into native mobile components before the app is deployed. NativeScript is one of the frameworks that does it.

Most Web applications would need to provide login and user authentication/authorization. The chances are that you’ve been offered by some apps to login using their FaceBook or Twitter account. Usually such authorization is implemented using OAuth protocol. You can set up authorization using privately installed OAuth server that fits nicely with RESTful Web services.

This book sampler will give you a taste of multiple facets of the modern development of Web and mobile applications. Some of the books are already released while others are still in the works, but you can reading drafts via Manning’s MEAP program.

For this sampler I’ve suggested selected chapters from the following books:

1. RxJS in Action MEAP

2. Angular 2 Development with TypeScript

3. React in Action MEAP

4. NativeScript in Action MEAP

5. OAuth 2 in Action MEAP

This is not a complete list and there are other fine books being released by many book publishers. Here’s my message to you

“Read.Study.Write.Repeat.”

Happy reading!

Dear community or my response to Dear JavaScript

I decided to write this blog after reading the post “Dear JavaScript” by James Kyle. In short, James write about how the anger and negativity in some posts/comments hurt people who work tirelessly developing open source software. I’d like to take this discussion a step higher and talk about online communities in general and growing the thick skin.

I do understand James’ feelings first hand. Been there. Produced a lot of free content online. Wrote more than a 1000 blogs in English. Recorded 500 audio podcasts in Russian . Published multiple free video trainings watched by hundreds of thousands people. In short, I’ve produced a lot of content. Some of it was of great quality IMHO, and some of it could be better.

At least I tried.

But no matter what content you produce, as long as it’s consumed by a dozen people expect getting some criticism, which, for the most part will be constructive, because these people belong to your close circle. But as the number of consumers grows, you’ll start getting angry or even hateful feedbacks. With thousands of consumers, expect direct insults.

Haters gonna hate.

It took me a while to stop paying attention to negative feedback as long as I believed that I did a good job. You can’t be loved by everyone. Let’s take my Intro to Java video. It was watched by more than a 100,000 people, got 1,000 likes and 18 dislikes. This tells me that I did a great job. Should I worry about 18 dislikes. Not a bit. Not everyone has to like my content, style, voice, or the shape of my nose. Vast majority of comments are positive and thankful except this one(I translate it from Russian): “This is almost the most stupid and disgusting presenter I’ve ever seen.” This comment put a smile on my face. I took me a while to grow thick skin, but if the majority of people approve your work, I’ll continue doing what I enjoy.

I’m following a very interesting person on Instagram. Her name is Nika. She travels the world, posts beautiful photos, and writes excellent notes (in Russian) to her posts. You can’t even imagine how many hateful comments she gets. Originally this photo  was taken by her teenage son Gregory, who created his own site. Here’s an abridged translation of their dialog:

– Mom, could you add a link to my Web site. I can go public already, can’t I?
– Sure you can, but first let me show you something. Here’s the collection of comments written about your mom (90% were written by women). These are their faces, and they will inevitably come to your site to watch you.
After reading silently for about five minutes Gregory’s face became pale, and he asked:
– Mom, why are they doing this? What’s wrong with them? Why do they hate you so much?
– Greg, this is not hatred. They tell us about themselves and their fears. I personally have nothing to do with this. They don’t care who to write about. I’m their mirror and it’s very painful for them to look into this mirror. Fear=pain=hatred. Are you ready? Are you sure you won’t get upset?
– Mom, don’t publish the link to my site.

Then Nika concludes. This may be not very pedagogical, but he’s a big boy now. Let him know the difference between “for what” and “why”.

In the past, most Internet users were consumers of some published content. Now anyone can easily produce and self-publish any content. Moreover, with the advances of blogging platforms, CSS, and typography no matter what you publish will look as a professionally produced article (regardless of its content). Yes, I’m talking about medium.com. Who cares that every blog on medium looks the same? They look better than the online edition of the New York Times.

Unfortunately, many social networks are poisoned by angry, destructive comments that may hurt good people like James Kyle. The only social network that stands out as a friendly place for everyone is StackOverflow. After earning the 2000 reputation you are allowed to edit posts of other users. Maybe that’s one of the reasons people love going to StackOverflow. No negativity there

So dear Internet community, be f@@king polite to other people. Respect the work done for you by others. Especially, if they did it for free. If you don’t like some content, suggest improvements. Don’t expose your black souls. Peace.

Categories Web

Angular 2: Implementing master-detail using router

In my blog about passing data to routes I mentioned that you can subscribe to parameters changing over time. In this blog I’ll show you how to do it by implementing master-detail functionality using the router.

Imagine, you have a list of products and, when the user clicks on one of the products, you need to show product details. There are different ways of implementing such functionality, but I’ll implement the use case when the product details functionality is implemented by a separate component that is created by the Angular router. The master part is represented by the list of mobile phones id/description, and the details about selected phone will be displayed by the component ProductDetailComponent that will be created by the router when the method Router.navigate() will be invoked for the first time. The following screen shot was take when the user selected the phone with ID=3. The bottom portion shows the details of this phone rendered by the ProductDetailComponent (on the cyan background) inside the <router-outlet>.

master-detail2

If the user will select another item from the list, its ID will be passed to the route and the respected product details will be displayed. Note that the URL will be change when the user selects different product.

Let’s start with the ProductDetailComponent. Angular router comes with the class ActivatedRoute that among other things stores the data received by the route. If you’ll read the source code of ActivatedRoute you’ll see the following properties there:

/**
* The matrix parameters scoped to this route. 
* The observable will emit a new value when
* the set of the parameters changes.
*/
params: Observable<Params>;

/**
 * The current snapshot of this route.
 */
snapshot: ActivatedRouteSnapshot;

In the previous blog I showed the example of using the snapshot property, which is exactly what the name states – a one time snapshot of the router state. The Router would create an instance of the ProductDetailComponent, where we’d inject the instance of ActivatedRoute and get the id of the phone:

  constructor(private route: ActivatedRoute) {
    this.productID = route.snapshot.params['id'];
  }

If the user would click on the link or invoke navigate() for the first time, the instance of the ProductDetailComponent would be created. But what if the instance of this component has already been created, but the user takes actions that results in multiple invocations of navigate() to the same route? The instance of ProductDetailComponent already exists, its constructor won’t be invoked again, and no new snapshots of the router states will be taken. This is where subscribing to an Observable stream comes in.

  constructor(private route: ActivatedRoute) {

    this.route.params.subscribe(
        params => this.productID = params['id']
    );
  }

The code of the constructor is still invoked once, but now it creates a subscription to the data stream that can be pushed to the route. Of course, if the user will navigate to a different route, the instance of ProductDetailComponent will be destroyed and detached from DOM, and the subscription will be over. But in our application we’ll configure just one route so the subscription will stay alive once created. Below is the entire code of the ProductDetailClass:

import {Component} from '@angular/core';
import {ActivatedRoute} from '@angular/router';

@Component({
  selector: 'product',
  template: `<h3 class="product">Details for product id {{productID}}</h3>`,
  styles: ['.product {background: cyan; width: 200px;} ']
})
export class ProductDetailComponent {
  productID: number;

  constructor(private route: ActivatedRoute) {

    this.route.params.subscribe(
        params => this.productID = params['id']
    );
  }
}

The code that configures the routes, renders the list of products and arranges the navigation is shown next.

import {Component} from '@angular/core';
import {Routes, Router} from '@angular/router';

const routes: Routes = [
    {path: 'product/:id', 
      component: ProductDetailComponent}
];

class Product {
    id: number;
    description: string;
}

@Component({
    selector: 'app',
    template: `
        <ul style="width: 100px;">
           <li *ngFor="let product of products"
            [class.selected]="product === selectedProduct"
            (click) = onSelect(product)>
              {{product.id}} {{product.description}} 
           </li>        
       </ul>
        
        <router-outlet></router-outlet>
    `,
    styles:[`.selected {background-color: cornflowerblue}`]
})
class AppComponent {

    selectedProduct: Product;

    products: Product[] = [
        {id: 1, description: "iPhone 7"},
        {id: 2, description: "Samsung 7"},
        {id: 3, description: "MS Lumina"}
    ];

    constructor(private _router: Router){}

    onSelect(prod: Product): void {
        this.selectedProduct = prod;
        this._router.navigate(["/product", prod.id]);
    }
}

The most interesting steps are the following:

1. We have configured one route that expects the product ID as a parameter:

const routes: Routes = [
    {path: 'product/:id', 
       component: ProductDetailComponent}
];

2. We asked Angular to inject the Router object so we can invoke its method navigate()

    constructor(private _router: Router){}

3. When the user selects a phone from the list, we invoke the click handler passing the selected product to it:

(click) = onSelect(product)>

4. When the product is selected, we want to navigate to the route configured in step 1. If this is the first time the user selects the product, the instance of ProductDetailComponent will be created, otherwise, the existing instance will receive the selected product ID.

onSelect(prod: Product): void {
    this.selectedProduct = prod; // to apply proper styles to the selected product

    this._router.navigate(["/product", prod.id]);
}

Angular uses RxJS and Observables in multiple places, and in this blog I’ve illustrated the use of observable stream with the router.

That’s all there is to it. To see this app in action, check out this plunk.

My Angular 2 presentations for 2017

In 2017 I’m planning to speak at several conferences related to development of Web applications with the new Angular 2 framework. Below is the list of my presentations (each one is 90-min long). All of them can be delivered as a 2-day workshop in your organization.

Mastering TypeScript

TypeScript is a superset of JavaScript, which allows you to be more productive in writing JavaScript applications. The syntax of this language is pretty easy to pick up for anyone who’s familiar with such object-oriented languages as Java or C#. During this presentation you’ll learn the syntax of this language and will understand the benefits it brings to the table.

Make a facelift to your Angular 2 app with UI libraries

Commercial applications need to be good looking, which means that you should pick up a rich library of UI components for your app. While Angular Material library offers two dozen of great looking components, this may not be enough for your application needs. The good news is that there are other libraries that you can use. In this presentation we’ll start with an overview of Angular Material components. Then we’ll proceed with another open-source library called PrimeNG, which offers more than 70 UI components. Finally, we’ll review the code of an Angular 2 app that uses both Angular Material and PrimeNG components.

Angular 2 for Java developers

Angular 2 is a complete re-write of the super popular Web framework AngularJS. According to Pluralsight survey, Angular leads the list of what developers want to learn in 2016. Angular 2 is a component-based framework that will have an effect in JavaScript community similar to what Spring framework did for Java. This presentation is an overview of this hot framework, which in combination with TypeScript, finally made Web development understandable for Java developers. At the end of the presentation you’ll see a sample Web application written in Angular 2 on the front and Java on the server.

Angular 2: Working with the component router

In this session you’ll see how to use the router that comes with Angular 2 Final. We’ll start with configuring the navigation in a simple app. Then you’ll see how to pass data to routes, work child routes, and create apps with multiple router outlets (auxiliary routes). We’ll also review a unit-test configuration for testing router. Finally, you’ll see how how to lazy load modules using the router.

Angular 2: Communication with the server via HTTP and WebSocket protocols

In this session you’ll see how create an Angular 2 app that can communicate with the servers via a pull (HTTP) and push (WebSocket) modes. We’ll program a simple Node server and then will go through a number of code samples that communicate with it using HTTP and WebSocket protocols. We’ll start with creating a simple NodeJS server, and then will enable it to handle HTTP requests from an Angular 2 app. Then you’ll see how to wrap a service into an observable stream. Finally, we’ll teach our server to perform a data push to an Angular 2 client using the WebSocket protocol.

Implementing inter-component communication in Angular 2

Angular 2 is a component-based framework with a well-defined API for passing data to and getting data from a component. Any application is a tree of components that often need to communicate with each other.
In this presentation you’ll see how to create reusable application components that can exchange data with each other in a loosely-coupled manner. You’ll see how components can communicate via a common parent or via an injectable service. You’ll see how to pass data using component router, input and output parameters, events and callbacks. You’ll also learn how to use projection (formerly known as transclusion) to pass HTML fragments to a component’s template. We’ll also touch upon the incorporation of the third-party JavaScript libraries into an Angular 2 app.

Using Observable Streams in Angular 2

Angular 2 includes RxJS, which is a library of reactive extensions built on the premise that everything is an observable stream.

Observables allow to introduce the push model to your application. First we’ll get familiar with the RxJS library, and then will continue reviewing observables in Angular 2. In this presentation you’ll see how to treat UI events, HTTP, and WebSocket connections as observable streams that push data. You’ll see how to wrap up any service into an observable stream so your application components can subscribe to it.

Angular 2 Tooling

Learning Angular 2 is easier than AngularJS, and developing in TypeScript is more productive than in JavaScript. But setting up the project and deploying the application is not straightforward. This presentation is not about the Angular 2 syntax. We’ll discuss the development process with Angular 2 starting from setting up the project to deploying an optimized application. We’ll start with discussing the Angular/TypeScript project structure and the proceed with such topics as using the module loader SystemJS, installing type definition files, bundling the app with Webpack and deployment in dev and prod. Finally, we’ll go through the process of scaffolding and bundling projects using the Angular CLI tool.