TypeScript Generics

TypeScript supports parameterized types, also known as generics, which can be used in a variety of scenarios. For example, you can create a function that can take values of any type, but during its invocation, in a particular context, you can explicitly specify a concrete type.

Take another example: an array can hold objects of any type, but you can specify which particular object types (for example, instances of Person) are allowed in an array. If you were to try to add an object of a different type, the TypeScript compiler would generate an error.

Generics syntax

The following code snippet declares a Person class, creates two instances of it, and stores them in the workers array declared with the generic type. Generic types are denoted by placing them in the angle brackets (for example, ).

class Person {
    name: string;
}

class Employee extends Person{
    department: number;
}

class Animal {
    breed: string;
}

let workers: Array<Person> = [];

workers[0] = new Person();
workers[1] = new Employee();
workers[2] = new Animal();  // compile-time error

Here we declare the Person, Employee, and Animal classes and a workers array with the generic type. By doing this, we announce our plans to store only instances of the class Person or its descendants. An attempt to store an instance of an Animal in the same array will result in a compile-time error.

Nominal and Structural type systems

After using generics in Java for 10 years, I quickly noticed that the syntax is the same and was about to check off this syntax element as “got it”. But it was a little too soon. While Java, C++, or C# use nomimal type system, TypeScript uses the structural one. In the nominal system, types are checked against their names, but in a structural system by their structure.

With the nominal type system the following line would result in an error:

let person: Person = new Animal();

With a structural type system, as long as the structures of the type are similar, you may get away with assigning an object of one type to a variable of another. Let’s illustrate it by adding the property name to the class Animal as seen on the screenshot below.

Now the TypeScript compiler doesn’t complain about assigning an Animal object to the variable of type Person. The variable of type Person expects an object that has a property name, and the Animal object has it. This is not to say that Person and Animal represent the same types, but these types a compatible. Trying to assign the Person object to a variable of type Animal will result in the compilation error “Property breed is missing in type Person”:

let worker: Animal = new Person(); // compilation error

Can you use generic types with any object or a function? No. The creator of the object or function has to allow this feature. If you open TypeScript’s type definition file (lib.d.ts) on GitHub and search for “interface Array,” you’ll see the declaration of the Array, as shown below.

The <T> in line 1008 means TypeScript allows you to declare a type parameter with Array and the compiler will check for the specific type provided in your program. The next code listing specifies this generic <T> parameter as <Person>. But because generics aren’t supported in JavaScript, you won’t see them in the code generated by the transpiler. It’s just an additional safety net for developers at compile time.

You can see another T in line 1022 in figure B.7. When generic types are specified with function arguments, no angle brackets are needed. But there’s no actual T type in TypeScript. The T here means the push method lets you push objects of a specific type into an array, as in the following example:

workers.push(new Person());

Creating your own parameterized types

You can create your own classes or functions that support generics as well. In the next listing, we defined an interface Comparator that declares a method compareTo() expecting the concrete type to be provided during this method invocation.

interface Comparator {                   // 1
    compareTo(value: T): number;
}

class Rectangle implements Comparator {    // 2

    constructor(private width: number, private height: number){};

    compareTo(value: Rectangle): number{   // 3
        if (this.width*this.height &gt;= value.width*value.height){
            return 1;}
        else  {
            return -1;
        }
    }
}

let rect1:Rectangle = new Rectangle(2,5);  
let rect2: Rectangle = new Rectangle(2,3);

rect1.compareTo(rect2)===1? console.log("rect1 is bigger"): 
                            console.log("rect1 is smaller") ;   // 4


class Programmer implements Comparator {    // 5

    constructor(public name: string, private salary: number){};

    compareTo(value: Programmer): number{  // 6
        if (this.salary &gt;= value.salary){
            return 1;}
        else  {
            return -1;
        }
    }
}

let prog1:Programmer = new Programmer("John",20000);
let prog2: Programmer = new Programmer("Alex",30000);

prog1.compareTo(prog2)===1? console.log(${prog1.name} is richer):
                           console.log(${prog1.name} is poorer) ;  // 7

1. Declare an interface Comparator with a generic type

2. Create a class that implements Comparator specifying the concrete type Rectangle

3. Implement the method for comparing rectangles

4.Compare rectangles (the type T is erased and replaced with Rectangle)

5. Create a class that implement Comparator specifying the concrete type Programmer

6.Implement the method for comparing programmers

7. Compare programmers (the type T is erased and replaced with Programmer)

Even though generics are erased during the JavaScript code generation, use them to minimize the number of runtime errors. When you use libraries or frameworks written in TypeScript, you have no choice but use generics to use the API provided by these libraries.

If you live in New York, stop by at the Java SIG meetup on August 23, 2017 where I’ll be delivering a presentation “TypeScript for Java Developers”.

JavaScript rest and spread operators

Back in 2015, the ECMAScript 6 spec was released and at the time of this writing, all major browsers (except the stubborn IE11) support its syntax. In this article, I’ll show you a couple of useful operators: rest and spread.

Due to lack of imagination, the creators of ES6 spec decided to use the same notation (…) for both rest and spread operators, but let’s not whine. If everything would be simple, our salaries would be lower. So let’s start with getting familiar with the rest operator.

Rest parameters

In ES5, writing a function with a variable number of parameters required using a special object called arguments. This object is similar to an array, and it contains values corresponding to the arguments passed to a function. The implicit arguments variable could be treated as a local variable in any function.

The rest operator is used to pass a variable number of arguments to a function, and it has to be the last one in the arguments list. If the name of the function argument starts with the three dots, the function will get the rest of the arguments in an array. The ES6 rest operator is represented by three dots (…).

For example, you can pass multiple customers to a function using a single variable name with a rest operator:

function processCustomers(...customers){
  // implementation of the function goes here
}

Inside this function, you can handle the argument customers the same way you’d handle any array. Imagine that you need to write a function to calculate taxes that must be invoked with the first argument income, followed by any number of arguments representing the names of the customers. The following code shows how you could process a variable number of arguments using first the ES5 and then the ES6 syntax. The calcTaxES5() function uses the object named arguments, and the function calcTaxES6() uses the ES6 rest operator:

// ES5 and arguments object
  function calcTaxES5(){

      console.log("ES5. Calculating tax for customers with the income ",
                             arguments[0]);   // income is the first element

      // extract an array starting from 2nd element
      var customers = [].slice.call(arguments, 1);

      customers.forEach(function (customer) {
          console.log("Processing ", customer);
      });
  }

  calcTaxES5(50000, "Smith", "Johnson", "McDonald");
  calcTaxES5(750000, "Olson", "Clinton");

// ES6 and rest operator
  function calcTaxES6(income, ...customers) {
      console.log("ES6. Calculating tax for customers with the income ", income);

      customers.forEach(function (customer) {
          console.log("Processing ", customer);
      });
  }

  calcTaxES6(50000, "Smith", "Johnson", "McDonald");
  calcTaxES6(750000, "Olson", "Clinton");

Both functions, calcTaxES5() and calcTaxES6() produce the same results:

ES5. Calculating tax for customers with the income 50000
Processing Smith
Processing Johnson
Processing McDonald
ES5. Calculating tax for customers with the income 750000
Processing Olson
Processing Clinton
ES6. Calculating tax for customers with the income 50000
Processing Smith
Processing Johnson
Processing McDonald
ES6. Calculating tax for customers with the income 750000
Processing Olson
Processing Clinton

See it in action on CodePen (click on the Console at the bottom to see the output): https://codepen.io/yfain/pen/WEjLwR?editors=0011

There’s a difference in handling customers though. Because the arguments object isn’t a real array, we had to create an array in the ES5 version by using the slice() and call() methods to extract the names of the customers starting from the second element in arguments. The ES6 version doesn’t require us to use these tricks because the rest operator gives you a regular array of customers. Using the rest arguments made the code simpler and more readable.

The spread operator

The ES6 spread operator is also represented by three dots (…) like the rest parameters, but if the rest operator can turn a variable number of parameters into an array, the spread operator can do the opposite: turn an array into a list of values or function parameters.

Say you have two arrays and you need to add the elements of the second array to the end of the first one. With the spread operator it’s one line of code:

array1.push(...array2);

You can also create a copy of an array as follows

let arrayCopy = [...myArray];

Finding a maximum value in the array is also easy with the spread operator:

const maxValue = Math.max(...myArray);

In some cases, you want to clone an object. In cases when you have an object that stores the state of your app, you may want to create a new object when one of the state properties changes. In other words, you don’t want to mutate the object but want to clone it with modification of one or more properties. One way to implement immutable objects is by using the Object.assign() function. The following code snippet will create a clone of the object first, and then will do another clone with changing the lastName at the same time:

// Clone with Object.assign()
const myObject = { name: "Mary" , lastName: "Smith"};
const clone = Object.assign({}, myObject);
console.log(clone); 

// Clone with modifying the `lastName`
const cloneModified = Object.assign({}, myObject, {lastName: "Lee"});
console.log( cloneModified); 

The spread operator offers a more concise syntax for achieving the same goals:

// Clone with spread
const cloneSpread = {...myObject};
console.log(cloneSpread);

// Clone with modifying the `lastName`
const cloneSpreadModified = {...myObject, lastName: "Lee"};
console.log(cloneSpreadModified);

See it in CodePen: https://codepen.io/yfain/pen/XaRGYa?editors=0011

If you haven’t been using spread and rest operators yet, it’s a big mistake. Huge.

This article is just an intro to using the rest and spread operators. For more info, read the docs here and here.

Angular CLI: dev and prod builds with JiT and AoT

I’m happy to announce that my colleague Anton and I started working on the second edition of our Angular book published by Manning. The new TOC is here. The major changes in the second edition are:

– Get rid of any mention of SystemJS – use Angular CLI only
– Replace the chapter on Webpack with the chapter on ngrx
– Add more code samples illustrating various features and techniques

I just finished re-writing the first chapter and would like to offer you a fragment that illustrates the use of Angular CLI for creating dev and prod builds. Your feedback is appreciated.

To make this article more practical, generate a new project Hello CLI using Angular CLi:

ng new hello-cli

Then build the bundles, start the dev server and open the browser on port 4200 by running a single command:

ng serve -o

Now goes the chapter fragment.

Production Builds

The ng serve command bundled the app files but didn’t optimize our Hello CLI application. Open the Network tab in the dev tools of your browser and you’ll see that the browser had to load 2.4MB to render this simple app. In dev mode, the size of the app is not a concern because you run the server locally and it takes the browser only 802 milliseconds to load this 2.4MB of code as shown below.

Now visualize a user with a mobile device browsing the Internet over a regular 3G connection. It’ll take 10 seconds to load the same Hello CLI app. Many people can’t tolerate waiting for 10 seconds for any app except Facebook (30% of the Earth population just lives on Facebook). We need to reduce the size of the bundles before going live.

Applying the -prod option while building the bundles will produce much smaller bundles by optimizing your code, i.e. it’ll rename your variables into single-letter ones, will remove comments and empty lines, and will remove the majority of the unused code. There is another piece of code that can be removed from the app bundles – the Angular compiler. Yes, the ng serve command included such compiler into the vendor.bundle.js. In the next section will talk about production builds and how to remove the Angular compiler from your deployed app.

JiT and AoT Compilations

Take a look at the code of the generated app.component.html.

<div style="text-align:center">
  <h1>
    Welcome to {{title}}!
  </h1>
  <img width="300" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxOS4xLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAw...">
</div>
<h2>Here are some links to help you start: </h2>
<ul>
  <li>
    <h2><a target="_blank" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
  </li>
  <li>
    <h2><a target="_blank" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2>
  </li>
  <li>
    <h2><a target="_blank" href="http://angularjs.blogspot.com/">Angular blog</a></h2>
  </li>
</ul>

For the most part, it consists of standard HTML tags, but there is one line that browsers won’t understand:

Welcome to {{title}}!

These double curly braces represent binding a value into a string in Angular, but this line has to be compiled by the Angular compiler (it’s called ngc) to replace the binding with something that browser would understand. A component template can include another Angular-specific syntax (e.g. structural directive *ngIf and *ngFor) that need to be compiled before asking the browser to render the template.

When you run the ng serve command, the template compilation is performed inside the browser. After the browser loads your app bundles, the Angular compiler (packaged inside vendor.bundle.js)performs the compilation of the templates from main.bundle.js. This is called Just-in-Time (JiT) compilation. This term means that the compilation happens in time of the arrival of the bundles to the browser.

The drawbacks of the JIT compilation are:

1. There is a time gap between the loading bundles and rendering the UI. This time is spent on JiT compilation. On a small app like Hello CLI this time is minimal, but in real world apps, the JiT compilation can take a couple of seconds, so the user needs to wait longer for just seeing your app.

2. The Angular compiler has to be included in the vendor.bundle.js, which adds to the size of your app.

Using the JiT compilation in the prod is discouraged, and we want the templates to be pre-compiled into JavaScript before the bundles are created. This is what Ahead-of-Time (AoT) compilation is about.

The advantages of the AoT compilation are:

1. The browser can render the UI as soon as you app is loaded. There is no need to wait for code compilation.

2. The ngc compiler is not included in the vendor.bundle.js and the resulting size of your app might be smaller.

Why use the word “might” and not “will”? The removing of ngc compiler from the bundles should always result in smaller app size? Not always. The reason being that the compiled templates are larger than those that use a concise Angular syntax. The size of the Hello CLI will definitely be smaller as there is only one line to compile. But in larger apps with lots of views, the compiled templates may increase the size your app so it’s even larger than the JIT-compiled app with ngc included in the bundle. But you should use the AoT mode anyway because the user will see initial landing page of your app sooner.

Creating bundles with the -prod option

When you build the bundles with the -prod option, Angular CLI performs code optimization and AoT compilation. Let’s see it in action by running the following command in our Hello CLI project:

ng serve -prod

Open the app in your browser and check the Network tab as shown in the next image. Now the size of the same app is only 120KB (compare to 2.4MB) and the load time is 573 milliseconds (compare to 802 milliseconds).

What a great result! Google home page weighs more than 200KB. As a matter of fact, the size of the app could be reduced even more after applying the gzip compression to the bundles. Note that the file names of the bundles now include a hash code of each bundle. Angular CLI calculates a new hash code on each prod build to prevent browsers from using the cached version if a new app version is deployed in prod.

Recently released Angular CLI 1.3.0 offers a new option –build-optimizer, which does a better job in eliminating unused code. Even in our simple app it reduced the size of this app to 111Kb. On larger apps the effect of this option can be even bigger. In one of our apps that uses Angular Material it reduced the app size from 290KB to 200KB (lots of dead code there?). The option –build-optimizer works with both ng serve and ng build commands.

ng serve -prod --build-optimizer

Shouldn’t we always use AoT? Ideally, you should unless you use some third-party JavaScript libraries which produce errors during the AoT compilation. If you run into this problem, turn the AoT compilation off by building the bundles with the following command:

ng serve -prod -aot=false

The next screen shot shows that both the size and the load time increased compared to the AoT compiled app.

We were using the ng serve -prod command, which was building the bundles in memory. If you’re ready to generate prod files, use the ng build -prod command instead. We’ll go over the process of building production bundles and deploying the app on the server in chapter 8.

The goal of this section was to get you started with Angular CLI, and we’ll continue its coverage in chapter 2.

Migrating your apps from AngularJS to Angular

So you have an Angular JS in prod and you want to migrate it to the latest version of Angular. The first question to answer is why? While talking to our clients, I’ve heard the following answers:

– We have a large app and it has issues with performance.
– Our company is moving to Angular/TypeScript and we want all apps to use these technologies.
– We need to improve performance of our AngularJS app
– Since all new apps will be written in Angular, it’s going to become hard to support apps written in two different languages and frameworks. The pool of developers who can/want write in AngularJS will be shrinking.

Any of the above answers sounds reasonable. But think about it for a moment. You have a working app with a certain functionality. After spending X amount of dollars your end users will get an app with the same functionality. Does it worth the trouble? Let’s say it does and the budget for the migration is approved.

Two approaches for migration

There are a couple of approaches to the AngularJS-Angular migration process.

1. Rewrite the app from scratch.

IMO, this is the best approach if your circumstances permit. A complete re-write can be the most cost-effective strategy. If you’re a manager, put your team through Angular training (live, online, videos, books). Allocate time and budget for getting your developers up to speed with Angular as the learning curve is steep and prior experience with AngularJS is not overly helpful. Then your developers will write the new version of the app as per best practices recommended for Angular/TypeScript projects. Ideally, your team should include a developer who has at least one year of practical development in Angular. If you don’t already have such a developer, hire one. He should be both a developer and a mentor.

But a complete rewrite may not be an option. Your existing (small-to-midsize) AngularJS app is in prod, works well, and the end users keep asking for new features that have to be released in prod on a regular basis. This means that you can’t just stop developing in AngularJS, and spending several months doing greenfield development is not an option.

You can’t do a complete rewrite if an existing app is large (think hundreds of views). In this case, a rewrite could take a couple of years.

2. Gradual migration

If you decide to go this route, start with reading the document titled “Upgrading from AngularJS“. It’s a well-written document, but you need to understand that it’s about migration from AngularJS to a completely different framework. Don’t be tricked by the statements like “Angular is a reimagined version of the best parts of AngularJS”. Angular is a different framework with different architecture and principles of building apps.

TypeScript, being a superset of JavaScript, requires some investment in learning too. But TypeScript is your friend. The learning curve for any JavaScript/Java/Python/C# developer is not steep, the tooling is great, optional static types make the transition from JavaScript easy plus you’ll get a great help from IDEs (autocomplete and compilation errors). In no time, you’ll see how your productivity is increased compared to writing in JavaScript.

Some die-hard JavaScript experts may continue bad-mouthing TypeScript, but be pragmatic. TypeScript allows making developers of any skill level (not just the superstars) more productive. Don’t trust me? A recent StackOverFlow survey nominated TypeScript as a third most loved language.

Plan your migration

You need to come up with a plan for your migration project. The plan will depend on how your current AngularJS app was written. While the Angular’s migration guide mentioned above recommends preparing your AngularJS app to have one component per file (see Rule 1 in the migration guide) and use module loaders, the chances are slim that your existing AngularJS app followed this rule. Refactoring your AngularJS app just to follow this rule is a project on its own; it may be costly and your refactored app would require additional testing and bug fixing.

The Angular migration guide explains how the AngularJS app should use component directives to simplify migration to Angular. Once again, changing your existing app to follow these guidelines is yet another project.

Depending on the production release schedule of the existing AngularJS app, you can pick one of two approaches for the migration:

– Feature by feature
– Route by route

When you migrate feature by feature, identify a group of component and services implementing this feature in the new Angular code.

Migrating route by route would also require a similar activity, but you’d need to pick a route and identify which components and services would need to be there. The route by route strategy works well if the views of your app are relatively simple and don’t use complex custom components.

If your AngularJS app has complex UI components, you may need to convert them first.

Running Angular and AngularJS side by side

The next step is to learn how the ngUpgrade and UpgradeModule work. The UpgradeModule serves as a bridge between the Angular and AngularJS parts of your app.

No matter how you’ll approach the migration, for some period of time your app will include two frameworks: AngularJS and Angular. When our company is involved with migration projects, we start with creating an Angular app that just bootstraps the existing AngularJS app as is with the help of the UpgradeModule.

With the UpgradeModule, you’ll run a hybrid app that’ll have two parts – one part will include Angular framework, and another – AngularJS. The components and services from the Angular part will communicate with their counterparts from the part written in AngularJS. Read the Angular migration guide about the differences in Dependency Injection (DI), change detection, and working with DOM.

While Angular DI is more flexible and allows either having services as singletons for the entire app or a specific component branch, in AngularJS services are always app-level singletons. This is not a big deal as in a typical Angular app we use app-level singletons anyway. In particular, you can use a singleton and DI for storing the state of the hybrid app. During the migration, you need to identify which services will be injected from Angular to AngularJS and those that will be injected in the opposite direction.

Components of both frameworks need to communicate with each other. If you’re not familiar with how to arrange a loosely-coupled component communication in Angular using injectable services, watch my video on the subject.

While running a mixed Angular/AngularJS app, the Angular framework will be responsible for triggering change detection of the entire app. Angular includes a library zone.js that serves as an execution context for all asynchronous processes of the app. On any change that may need to update a UI, it makes a single pass through the entire component tree and triggers the UI updates. There is no need to invoke $scope.$apply() as it’s done in AngularJS. In a hybrid app, on any async change that would start Angular change detection, the UpgradeModule will invoke $rootScope.$apply() in your AngularJS code.

Finally, roll-up your sleeves, start reading the AngularJS code and gradually implement it in Angular.

Automating deployment

Don’t forget about re-thinking your deployment process. Most likely you have an automated deployment implemented using Gulp or Grunt. In Angular apps most of the features that we had to manually configure in AngularJS are provided by the tool called Angular CLI. We wrap Angular CLI commands into npm scripts and add Gulp tasks if need be. It takes only several lines of code in npm scripts to build the bundles for deployment in Angular. In this video I show how to write a script that will build the Angular bundles and deploy them under a Java Spring server. If I wanted to gzip the files before deployment, I could have added one more line like `“postbuild:prod”: “gulp –gulpfile compress.js”` that invokes my script that uses the Gulp plugin for compression.

Good luck with your migration projects!

Advanced Angular course – need your input

We started receiving requests for teaching an advanced Angular workshop. My colleague Anton and I started preparing the courseware and are planning to offer such a workshop this fall. Below is a draft of this course outline, which will start with refactoring and upgrading the ngShop app that we’ve  created for one of our Intro to Angular courses.  Please take a look at the draft below, and if you see some topics that should be added to this workshop, please leave comments to this blog. Thank you!

Advanced Angular Course (draft)

  1. Using UI libraries: Angular Material and PrimeNG

    1. Adding @angular/material package to the ngShop application
    2. Configuring custom theme / SCSS
    3. Laying out component with @angular/flex-layout library
    4. Programmatically changing UI layouts with MediaQueryList
    5. Combining Angular Material 2 and the PrimeNG UI components
  2. Modularizing Angular application:

    1. Minimizing the initial app payload by splitting it into modules
    2. Lazy-loaded modules and preloaders
    3. Adding new Admin module to ngShop
    4. Configuring a lazy-loaded route for Admin module
    5. Configuring route resolvers
  3. Application Security with JWT

    1. Intro to JWT-based authentication
    2. Adding a JWT-based Login page
    3. Authorizing access to the Admin module via route guard
    4. Adding JWT token to the HTTP requests required authorized access
    5. Handling Unauthorized errors
  4. Dynamically adding components to your app

    1. Creating a dynamically configurable  Dashboard page
    2. Dynamically adding components with ComponentFactoryResolver
    3. Dynamically adding components with
  5. Advanced work with Forms

    1. Creating custom form controls. ControlValueAccessor.
    2. Splitting complex forms into multiple Angular components
    3. Validating form groups
    4. Refactoring the Checkout page of ngShop
    5. Adding an inventory page with a data grid
  6. End-to-end testing with Protractor

  7. Production deployment

    1. Customizing Webpack build configuration and  ng eject
    2. Building Angular application on the Continuous Integration server
    3. Running tests on CI
    4. Automatic deployments to the nginx server
    5. Configuring HTTPS
    6. Combining multiple Angular apps under a single domain
    7. Server-side rendering with Angular Universal
  8. Refactoring ngShop to introduce state management  with ngrx

    1. Benefits of  unidirectional data flow
    2. Managing state with @ngrx/store
    3. Time-travelling debugging with @ngrx/store-devtools
    4. Using  HTTP APIs with @ngrx/effects library
    5. Integration with the router via @ngrx/router library

 

My presentations and workshops in 2017


This is a list of presentations and workshops that Yakov Fain offers in 2017. If you’d like to invite Yakov to deliver these talks/workshops at your organization, please send an email at training@faratasystems.com. To get familiar with Yakov’s teaching style, watch his Youtube Java tutorial.

Presentations

Modern JavaScript – 70 min

In this presentation, you’ll learn how to write code using the latest syntax of JavaScript. While most of the apps use the ES5 version of the language, majority of the modern web browsers fully support the ES6 specification. Some of them started supporting the ES7 and ES8 syntax. In this presentation you’ll learn how to use classes, fat arrow functions, destructuring, spread and rest operators, promises, async-await, and modules.

Mastering TypeScript – 90 min

In this presentation, you’ll learn how to write code in TypeScript, one of the most loved languages today.TypeScript is a superset of JavaScript, which allows you to be more productive in writing JavaScript applications. Per StackOverflow developers survey TypeScript is the 3rd place in the most loved languages and 5th in most wanted. 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 TypeScript and will understand the benefits it brings to the table.

Angular Tooling – 90 min

Learning Angular is easier than AngularJS, and developing in TypeScript is more productive than in JavaScript. But you need to know your tools to create, bundle, and deploy your app.This presentation is not about the Angular syntax. We’ll discuss the development process with Angular starting from setting up the project to deploying an optimized application. Most part of this presentation is about using Angular CLI. We’ll start with generating a new project, and then discuss such subjects as configuring proxies, working with environment variables, automating builds with npm scripts, and more.

Communication with the server via HTTP and WebSocket protocols in Angular – 90 min

In this session, you’ll see how to create an Angular 4 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 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 client using the WebSocket protocol.

Angular for Java developers – 90 min

Angular is a complete re-write of the super popular Web framework AngularJS. Angular is a component-based framework that will have an effect in JavaScript community similar to what Spring framework did for Java. This presentation is a high-level overview of Angular, which in combination with TypeScript, finally made Web development understandable for Java developers. At the end of the presentation, you’ll see how to deploy Angular app can communicate with the Spring Boot backend.

Make a facelift to your Angular app with UI libraries – 90 min

In this presentation, you’ll see how to create a nice looking UI with Angular Material 2 and PrimeNG components.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 2 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 2 components. Then we’ll proceed with another open-source library called PrimeNG, which offers more than 70 UI components.

Implementing inter-component communication in Angular – 90 min

Angular 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. 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 the router, input and output parameters, events and callbacks. You’ll also learn how to use projection to pass HTML fragments to a component’s template. You’ll see how to pass parameters to routes. We’ll also touch upon the incorporation of the third-party JavaScript libraries into an Angular 4 app.

Working with the Angular router – 90 min

The Angular framework includes a powerful component router. In this session, you’ll see how to use the router that comes with Angular 4. 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 the app router. Finally, you’ll see how to lazy load modules using the router.

Using Observable Streams in Angular – 90 min

Angular includes RxJS, which is a library of reactive extensions built on the premise that everything is an observable stream. Angular includes RxJS, which is a library of reactive extensions built on the premise that everything is an observable stream. Observables introduce the push model to your application. First, we’ll get familiar with the RxJS library, and then will continue reviewing observables in Angular.You’ll see how observables are used to handle events, forms, the router, and HTTP requests. We’ll talk about using subjects, implementing the mediator design pattern, and more.

RxJS essentials – 90 min

Libraries of reactive extensions exist in many programming languages. RxJS 5 is a popular library of reactive extensions for JavaScript. This library is used for transforming and composing streams of data. RxJS promotes the push model where the data flow through the algorithms of your application. RxJS is not a framework and can be used in any JavaScript app. Using RxJS allows writing certain portions of your app by composing functions where you see fit. You’ll learn how to create observable data streams, what are the roles of observers and subscribers, how to apply and compose operators to process the data emitted by observables, how to compose multiple data streams and more.

Reactive thinking with RxJava2 – 70 min

This presentation is about asynchronous programming in Java, where the streams of data are handled in a non-blocking fashion. We’ll talk about Reactive Streams and specifically about the RxJava2 library that may change the way you design Java applications. You’ll see how to consume streams of events, deal with backpressure, and apply a variety of operators offered by this library, which requires a different way of thinking about writing code.

JHipster: Bringing together Angular and Spring Boot – 70 min

JHipster is a popular open-source code generator that automates creation and configuration of a Web project that uses the Angular framework on the front and Java Spring Boot on the back. We’ll start with a simple example where an Angular app consumes the REST service from Spring Boot. Then we’ll proceed with an intro to JHipster followed by the generation of a new Angular/Spring Boot app from scratch. This will be a CRUD app of the following architecture: a gateway (the front end), a microservice (the back end), and a service discovery server.

Hands-on workshops

Developing Web apps with Angular and TypeScript – 3 days

Participants of this workshop will gain practical skills while exploring the best practices and principles of developing Angular applications and get familiar with multiple sample applications illustrating solutions for real-world challenges. During this course, we’ll cover all the latest APIs (routing, dependency injection, forms). At the end of each day, the participants will spend an hour working on the front end of a sample application “Online Auction”.

Angular Material 2 Applied – 1 day

This hands-on workshop is for developers who are already familiar with Angular. Under the instructor’s guidance, participants will work on the front end of the online store application, which uses Angular and the library of UI components Angular Material 2. By the end of the day, each participant will develop an online store with a shopping cart the will look and work like this one. This workshop assumes participants are already familiar with Angular. This workshop is NOT an Angular intro.

Angular: Advanced Topics – 3 days

This workshop is still in the works and will be offered in September of 2017. The participants of this workshop are expected to have a working knowledge of Angular. In this workshop, we’ll cover such topics as state management, authentication, advanced work with forms, themeing, modularization, server-side rendering, page layouts and more. Stay tuned.

BIO

Yakov Fain works as a Solutions Architect at Farata Systems that offers consulting and training services in developing of the Web Apps with Angular and Java. A Java Champion, he has taught multiple classes and workshops on the web and Java-related technologies, presented at international conferences, and published more than a thousand blog posts (see https://yakovfain.com). Yakov authored and co-authored a number of technical books on programming including the Amazon bestseller “Angular 2 Development with TypeScript”. He leads Princeton Java Users Group.