The Road to Angular 2.0 part 3: Types

Intro I gave a presentation at the GOTO conference in Amsterdam titled: The Road to Angular 2.0. In this presentation, I walked the Road to Angular 2.0 to figure out why Angular 2.0 was so different More »

The Road to Angular 2.0 part 2: ES6

Intro I gave a presentation at the GOTO conference in Amsterdam titled: The Road to Angular 2.0. In this presentation, I walked the Road to Angular 2.0 to figure out why Angular 2.0 was so different More »

The Road to Angular 2.0 part 1: Template Syntax

Intro A couple of weeks ago I gave a presentation at the GOTO conference in Amsterdam titled: The Road to Angular 2.0, in this presentation, I walked the Road to Angular 2.0 to More »

CORS with Spring MVC

In this blog post I will explain how to implement Cross-Origin Resource Sharing (CORS) on a Spring MVC backend. More »

Ebase Xi – Unsafe by Default – XXE

In my previous blog post I questioned the safety of the default configuration of Ebase Xi. I knew then that something was wrong as I had already found and reported two vulnerabilities More »

 

The Road to Angular 2.0 part 3: Types

Intro

I gave a presentation at the GOTO conference in Amsterdam titled: The Road to Angular 2.0. In this presentation, I walked the Road to Angular 2.0 to figure out why Angular 2.0 was so different from 1.x. This series of blogposts is a follow up to that presentation. theroadtoangular4

Types

Last week we looked at ES6, the next version of JavaScript, and how it is going to change the way we write our Angular 2.0 code. However ES6 was not enough for the Angular 2.0 team. They wanted to add types and annotations to JavaScript. So what the Angular team did was create their own language, called AtScript, which compiled down to JavaScript, which included types and annotations. Microsoft was also working on a language with types which transpiles back to ES5. That language is called TypeScript, and has been developed since 2012. The only thing TypeScript missed, according to the Angular 2.0 team, were annotations. So the two teams got together and the Angular team convinced the TypeScript folks to add annotations. Now there was no more need for AtScript, and it was abandoned in favor for TypeScript. Why create your own language when there is already a better alternative?

TypeScript

TypeScript is a superset of JavaScript, this means that all valid ES5 is valid TypeScript code. This means you can copy and paste the JS you write today and paste it in a TypeScript file and it will just work. Of course TypeScript also adds functionality such as types and annotations that do not have an equivalent in JavaScript. Hence not all valid TypeScript is valid JavaScript. Visually TypeScript looks something like this:

TypeScript

TypeScript is a superset of ES5, it wraps ES6, so you can use all ES6 features, and on top of that it adds types and annotations.

Types

In TypeScript you can add static types to JavaScript code. Consider the following example:

As you can see the type of the ‘name’ parameter, of the greeter function, is  type string. The return value of the greeter function is a string as well. Trying to give a number to the greeter function results in a type error at runtime:

Types are not limited only to primitives, you can also use ‘classes’ as types:

In the above example you can see how the the array named ‘persons’ only accept objects of type ‘Person’. Basically how generics works in C# and Java and other strongly typed languages.

Annotations

One of the reasons for the Angular team to stop working on AtScript is that TypeScript 1.5 promised to include annotations. Lets dive into what annotations can do by looking at some Angular 2.0 code:

Annotations are always prefixed with the @ symbol. This means that in the code above there are two annotations: @Component and @View. Note that you can also define your own annotations if you want to, @Component and @View are not “built” into TypeScript, they were created by the Angular team. What an annotation does is decorate a class with extra functionality in a very succinct way. With very little code you can add great a great deal of functionality. Lets look at the @Component and @View annotations from the example above to demonstrate this.

@Component

@Component tells Angular how it should recognize a component. In this case that it should recognize a PersonComponent whenever it sees an HTML element called person. So if you have the following code inside of a HTML template:

Angular will instantiate a PersonComponent.

@View

The @View annotation tells Angular what the template for a particular component is. In the case of the code snippet that defined a PersonComponent, the templates is a HTML paragraph (<p>) with a binding to ‘name’. Note that you could also put your template in a separate file and use templateUrl to retrieve the template, just like you could do in Angular 1.x.

Benefits of Types

We have now seen some TypeScript in action including static types and annotations. But what makes ‘types’ so great? After all we have been using JavaScript for years without the need for types at all. So why have types at all?

IDE and text editors love types

The more static information you provide an IDE the better it can help you write your code. Static types enable better autocompletion, better refactoring support and better code navigation. For example: when your editor sees you writing a function and it knows that it takes two numbers and returns a string, it can show a popup window with that information:

typescript-typehint

For the TypeScript team this extra productivity gain is very important. They even provide ways to autocomplete code that was not written in TypeScript. They do this by creating files that annotate other open source libraries or frameworks by defining TypeScript interfaces for them. These files have the .d.ts extension, where ts stands for TypeScript and .d. for definition, and can be used to make your life easier. There is even a GitHub repository with high quality .d.ts files: https://github.com/borisyankov/DefinitelyTyped

Types help you show your intent

Types are not only useful for IDEs, you the human programmer has benefit from them as well. Having type information makes it easier to reason about other people’s code, and even your own code three months down the line.

Is TypeScript required?

TypeScript is not required by Angular 2.0 you can still write ES5 or ES6, and even Dart and never use TypeScript at all. Which is also what the official docs at angular.io are saying, in fact they show ES5 examples next to every TypeScript example. That being said I think writing ES5 or ES6 is not going to be feasible, because I think every tutorial on Angular 2.0 is simply going to assume you use TypeScript. So if you insist on using ES5 or ES6, you will constantly have to rewrite TypeScript examples from the web back to ES5 or ES6 yourself.

I think it is best that you bite the bullet and use TypeScript. But since TypeScript is a superset of JavaScript you can choose when to use TypeScript and when to use pure JavaScript. You can mix and match as you please, this is especially handy when migrating from Angular 1.x to 2.0, but more on that in a later blog post.

In what language is Angular 2.0 is written?

Ever wonder why Angular 1.x is called AngularJS and Angular 2.0 is just Angular 2.0 sans the JS? That is because Angular is no longer just a JavaScript framework, instead it supports multiple languages. Angular 2.0 will support: ES6, ES5, TypeScript and Dart. Dart is a Language by Google that was supposed to transplant JavaScript as the scripting language of the browser. Recently Google announced they will not add Dart to Chrome but will transpile Dart to JavaScript instead. So what do they write Angular 2.0 itself in? The answer is in TypeScript, but they have Dart and JS Facades that help compile Angular 2.0 to JS and Dart versions. Here is a infographic from the Angular 2.0 team that shows how that works:

Angular 2.0 pipeline

You can read the graph as follows: Angular 2.0 is programmed in TypeScript (utmost left) and there are two facades one for JavaScript and one for Dart. The purpose of these facades is making it possible to write idiomatic API’s for code for both JS and Dart. This means that both languages get Angular’s API in a form that is best suited for that language. From there the traceur compiler outputs JavaScript and Dart versions of the framework.

When you write Angular 2.0 in Dart you write your application with Dart, using the Dart Angular API facade. This is what the two yellow ‘Dart’ blocks represent in the lower part of the graph.

When you choose to write your Angular 2.0 code in JavaScript you can choose between ES5, ES6 and TypeScript. But you will use the JavaScript API for all three of them. This is what the blue ‘JS’ part in the top part of the graph represents.

One CLI(hopefully) to rule them all

A colleague of mine asked my while he was reviewing this blogpost: “What do I have to do to use TypeScript in Angular 2.0?”. Which is a valid question, after all we have seen this complex graphs with all these facades, but we have no idea on how to use it in our projects.

The answer is that there is no answer yet on how to best build an Angular 2.0 project. But there is hope, the Angular team got together with the React team to discus common ground, and in the notes, Igor from the Angular team, discusses the need for a Command Line Interface (CLI). He states that the Angular is building a CLI that will, and I quote:

  1. Scaffold.
  2. Skeleton files
  3. Set up build
  4. Set up testing environment

By “Scaffold” I think Igor means generating entire base Angular projects, and by “Skeleton files” generating very specific files such as unit test, e2e test and services. “Set up build”  probably mean setting up TypeScript, Dart, ES5  or ES6 depending on the language that you choose. “Set up testing environment” means that it will setup karma and protractor for unit and e2e tests.

The Angular 2.0 team took a page from the Ember playbook, because Ember has had CLI for quite some time. The effect of having a CLI which has first class support and is created the Ember team itself, means that every Ember application out there, uses the same infrastructure to build Ember applications. Plus the Ember build system supports plugins, built on top of the ‘default’ CLI. This makes for a very powerful standardised way to build Ember applications. Having a big community that uses same tools makes these tools better.

From the meeting notes it is clear that the Angular team is working with the Ember guys to kickstart their own CLI:

We’re working with the Ember CLI team who are extracting reusable bits.  Working with Joe from broccoli and reusing those bits. Current changing the Angular build from gulp to broccoli. Working with the NPM team on package management and resolution. The package managers that exist today aren’t good, but NPM is the closest of all of them.

How this CLI will work exactly is currently still unknown, when there is more information available expect an update from me. That being said I think this is the Angular CLI is a very positive development for us, the Angular community..

Want to know more?

TypeScript adds a lot more functionality on top of JavaScript which I have not covered in this blogpost. Here are some TypeScript resources:

Conclusion

TypeScript was included into Angular 2.0 to allow us to statically define types, which help us write more readable code. TypeScript also includes annotations which allows us to write very little code but achieve much. It gives our IDEs type information to help us be more productive by providing better autocompletion.

So even though you are not forced to use TypeScript I definitely recommend that you do.

We’ve also seen that Angular 2.0 is no longer a pure “JavaScript” framework but that it supports multiple languages: JavaScript (ES6, and ES5), TypeScript and Dart. The new “CLI” will hopefully make it easy to setup Angular 2.0 projects in a way that the whole Angular community can benefit from it.

In previous weeks and this weeks we have been looking at some mechanical changes in Angular. Things that simply change the way we write Angular, next week we are going to look at components, which will change the way we think about Angular.

The Road to Angular 2.0 part 2: ES6

Intro

I gave a presentation at the GOTO conference in Amsterdam titled: The Road to Angular 2.0. In this presentation, I walked the Road to Angular 2.0 to figure out why Angular 2.0 was so different from 1.x.

This series of blogposts is a follow up to that presentation.

theroadtoangular3

ES6

Last week we discussed the new template syntax in Angular 1.x. This week it is time to discus ES6 and how it affects Angular 2.0.

ECMAScript 6 is the next version of JavaScript. The specs have been frozen and now it is up to the browser vendors to implement them. ES6 brings us some exiting new features. Let’s take a whirlwind tour and look at some of them.

Whirlwind tour

Fat Arrows

JavaScript is becoming more ‘functional’ in each iteration. ES5 added: map, reduce, filter and more. These functions take other functions as arguments. The functions that are passed in as arguments become less readable when they are inlined. For example this is quite verbose:

With ES6′s ‘fat arrow’ notation, writing lambda expression (anonymous functions) becomes really easy:

Fat arrow was created to allows us to write really short function definitions. Let’s look and break down another example:

Here you can see the function ‘square’ being defined as: x => x * x. What this says is: define a function with one parameter called x, which evaluates to x * x. The value of the expression is implicitly the return value, so there is no need for a return statement.

You can also define functions which take multiple parameters like so:

When creating a function with multiple parameters you must define them within parentheses.

You can also have multiple statements within a fat arrow by using brackets:

The fat arrow also has one other nice property: it doesn’t change the ‘this’ context. Compare and contrast the following ES5 and ES6 code:

setTimeout normally changes the ‘this’ context, which is why in ES5 you often bind ‘this’ to some variable for later use. In the example this variable was called ‘self’. The fat arrow keeps the outer ‘context’ of where it was called, in the example above ‘bert’ would be ‘this’. This makes ‘this’ act a little more as you would expect it to work. For more info see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Const

In ES6 you can define constants which cannot be reassigned via the ‘const’ keyword:

Constants cannot be reassigned, but they can be changed:

Constants are lexically scoped:

NAME is created inside the scope for the greet function. Outside of the greet functions NAME is not defined.

Let

‘let’ is a lot like ‘var’ except it is scoped to the ‘nearest’ closing block. For example:

Here you can see that ‘x’ is only available inside the ‘if’ block because that is where the ‘x’ was defined. If x was defined with a var however, the number 10 would have been printed twice. So let allows you to scope variables more tightly.

However let definitions are accessible in child scopes:

Redefining a let in a child scope does not affect the outer scope’s let definition, because a let is defined per scope, for example:

When you try to redefine a ‘let’ in a child scope by using the ‘let’ from the parent scope you get a ReferenceError:

This can be explained because in the statement: let x = x + ‘ world!’ the second ‘x’ refers to the ‘let x’ before the statement, and not the let x = ‘hello’ in the scope above. Within x + ‘ world!’ the let is still uninitialized  which causes the error.

Destructuring

Destructuring makes it easy to get values from complex objects and assign them to variables.

For example to get certain properties from an object and assign them:

You can do the same thing for ‘positions’ in an array:

You can use destructuring on a functions parameters too:

In the example above you can see both array and object destructuring happen in the moveBy function. What makes destructuring powerful is that it allows you to program to the ‘shape’ of the data structure. One thing about destructuring objects is that you can name the binding whatever you want. For instance, you could rewrite moveBy to this:

Whatever the ‘value’ of the key is becomes the binding for the variable in the function. So

what  {x: oldX} says is: there’s a key called x in the first parameter and I want to name it oldX.

Classes

JavaScript has prototypical inheritance, which makes it stand out from other languages, which use the more traditional classical inheritance such as C++, Java, Ruby, Python, C# and Objective-C. People coming from those languages would often create libraries that would use JavaScripts prototypical inheritance to mimic the more traditional classical inheritance.

ES6 gives us some syntactic sugar to make the more traditional classical inheritance possible, without having to use a library. It is important to note that behind the scenes ‘classes’ are still implemented using prototypical inheritance. Here an example:

The function ‘constructor’ is the constructor for that class, you cannot add multiple constructors via method overloading.

  •  ’super’ is used to call the parent constructor, in Human’s case that is Living.
  • The ‘get’ before isAlive means isAlive is a computed property. See get. This makes this.isAlive possible without parenthesis.
  • The ‘set’ before alive means you can set the value via assignment. This makes human.alive = false possible.
  • You can only extend one class at a time, multiple inheritance is not possible.

Generators

Generators are complex creatures that allow for some pretty awesome functionality. I doubt that you ever need to write a generator yourself, but frameworks creators can use it to make your life easier.

So what is a generator? A generator is a function that can be paused mid execution to give or receive values. It does so via the ‘yield’ keyword. Lets look at a simple generator:

In the example above we define a generator called threeCounter, it will give a number when it is called, after it has been called three times it is done. When you call counter.next you are given an object, the object has two properties: value and done, value is what the generator yielded, and done is a boolean which says if the generator has any new values to give.

You can instantiate a generator as many times as you want:

Each generator you create acts independently from other generators of the same type. I would like to say that calling a generators creates “instances” of that generators, like calling new on a class would. Perhaps it would have been better if generators were created with the ‘new’ keyword as well.

A generator is also an iterator, this means we can use it inside for each loops:

You can make generators that never stop providing values, for instance here’s a generator which creates class names for a zebra striped tables:

So even though the zebraGenerator has a while(true), it doesn’t run in an infinite loop, it stops each time there is a yield and provides the caller with a color.

We’ve seen how we can get value’s from a generator but we can also provide generators with values:

I know this example above is kind of contrived, but it demonstrates how to send values from the outside to the generator by using generator.next(42). You can also see that you can pass parameters to the generator function itself. In the above example I gave the string ‘massiveCalculation’ as a parameter, so the printer could make a nice header.

Passing values to generators is typically something library creators use to make our lives easier. For example:

This is from a library called js-csp, with it you can create Go like channels. In the example above

a channel for ‘mousemove’ events is created, and it is consumed using yield to print the location

of the mouse. With channels you can implement consumer and producer like patterns to manage

asynchronous events.

Another cool example uses generators make asynchronous code look like synchronous code:

This “co” function comes from the Co library, it lets you yield promises to “co” so it can handle the asynchronous parts of the code. It will resume running the code once all promises are resolved, this way you don’t have to write the then or error functions. This makes the code look synchronous, which makes the code easier to understand.

Here is a really exhaustive look at generators from ES6 guru Dr. Axel Rauschmayer.

Of course Co is just a bridge until ES7′s ‘await‘ syntax arrives!

Modules

So there is a lot of cool new stuff in ES6, but there is still one problem: how are you going to share all the classes, generators, and variables you have made? Until a couple of years ago the most common way was to give people a JS file and namespace your code, something like this:

This way you had private variables and created an API you exposed to some global variable. There are many downsides to this approach:

  • Name clashes with if some other library uses the $ sign other than you
  • Cannot import specific functions, you must take everything.
  • Cannot load modules programmatically / lazily.

Luckily ES6 has added support for creating modules. Let’s define an ES6 module:

We can then import the module above in a couple of ways:

The examples above show how versatile the new import syntax is. It is easy to prevent name clashes because there are so many ways to rename imports.

Want to know more?

Here’s a list of resources with even more examples. I recommend going through the first two:

https://github.com/lukehoban/es6features

https://github.com/google/traceur-compiler/wiki/LanguageFeatures

http://davidwalsh.name/es6-generators

http://www.2ality.com/2015/03/es6-generators.html (exhaustive look at generators)

http://jakearchibald.com/2014/es7-async-functions/ (technically ES7 but it is to awesome to ignore)

http://www.2ality.com/2014/09/es6-modules-final.html

ES6 and Angular 2.0

By now you have a pretty good idea of some of the features that ES6 adds to JavaScript. So what does it have to do with Angular 2.0?

The first thing is that Angular 2.0 will use classes a lot more instead of functions. Everything from Directives and Services will be classes in 2.0.

But the most important thing is that 2.0 uses ES6’s module system instead of having a custom module system that 1.x had. This greatly affects the way we write the JavaScript part of our Angular 2.0 code.

Sneak peak

Here is a small example on how you would use modules in Angular 2.0:

Angular 1.x’s module system

So what was wrong with the 1.x module system? Lets look at an example:

In the module definition above we see a factory called “userFactory” being assigned to the

“users” module. The “userFactory” has a dependency on the $http module that Angular 1.x provides.

The first downside to the Angular 1.x module system is that it is string based. This makes the module system brittle: one spelling mistake and the whole thing falls down like a house of cards.

The second downside is that in order to survive minification (jsmin) you must declare all dependencies inside of an array as strings. This is why ‘$http’ is declared inside the array as a string, and as $http, the variable, in the function. You can use ngAnnotate so you don’t have to write this code manually, but it is still a hassle.

The third, and most important downside, is that Angular 1.x modules only work inside the Angular world. If you have found a great library that was written in pure JavaScript without Angular in mind, you must jump through hoops to get it working inside Angular. The same is also true in reverse, if you have a great Angular module and you want to use it outside of Angular, you are going to have to rewrite the code.

Conclusion

By embracing ES6 and its module system it will become much easier to use existing non Angular JavaScript code in an Angular project, and vice versa.

This is not only true for Angular but also true for other frameworks as well such as Ember, React and Knockout. Sharing code between frameworks is going to be easier than never before. ES6 modules will act as a bridge between frameworks and the greater JavaScript world.

I hope that the ES6 modules system will unite the JavaScript community.

So in conclusion when you hear about the death of the Angular 1.x module system, thats a good thing. We are getting a great alternative in ES6 modules in return.

Next week we will look at Types, and why the Angular team thought ES6 alone was not enough!

The Road to Angular 2.0 part 1: Template Syntax

Intro

A couple of weeks ago I gave a presentation at the GOTO conference in Amsterdam titled: The Road to Angular 2.0, in this presentation, I walked the Road to Angular 2.0 to figure out why Angular 2.0 was so different from 1.x.

This series of blogposts is a follow up to that presentation.

The Road

When the first details about Angular 2.0 emerged, my initial response was: “Wait, what?!” So many things will change from version 1.x to 2.0, is it even Angular?

So I started digging through design documents, meeting notes, blogposts, and watched ng-conf videos. I quickly discovered a theme: The web will fundamentally change and Angular must evolve with it.

Web Components are coming, ES6 is around the corner, TypeScript was invented. This series of blog posts takes you through these new innovations and shows you how they have influenced Angular 2.0’s design.

I like to visualise all of the changes from Angular 1.x to 2.0 as a road. On this road we will come past various places that represent changes to Angular 1.x. Throughout this series of blog posts we will visit each of these places, and dive into how and why they have influenced Angular 2.0’s design. Here is the Road to Angular 2.0:

theroadtoangular

Template Syntax

Angular 2.0 has a new template syntax, which is radically different from 1.x. These changes made to the template syntax caused a strong negative reaction amongst the Angular community. It seemed like the Angular teams changed the heart of Angular for no good reason.

Now it seems we must learn Angular 2.0 all over again. But fear not, once you understand how the new template syntax works, and you know the reasoning behind it, it will make sense.

The new binding syntax

Let’s look at the differences in the bindings syntax between the two versions of Angular:

Angular 1.x

Angular 2.0

The example above shows a username an image and an up-vote button.

The first thing to note is that the first line is exactly the same in 1.x and 2.0. String interpolation is here to stay, so at least that part is still familiar.

The second line of code shows us the first difference in the new template syntax. Instead of using the ng-src directive in Angular 2.0 we see [src]. The brackets represent a binding to a property, this means that when the value changes in the “controller” the value is updated in the view as well.

The third line shows the new event syntax, whereas we used the special ng-click directive in 1.x we simply surround the event by parenthesis in 2.0.

Why change the binding syntax?

The main reason the syntax changed is unification. Lets look at the following line of 1.x template code:

In this code we use ng-src to fetch a template. If you take a step back from Angular and look at the code as a novice, who doesn’t know Angular,  you could ask: Why not simply write:

The reason of course is that the browser will try to fetch: {{ user.imageUrl }} from the server. This is because the browser doesn’t understand Angular’s string interpolation syntax.

So in Angular 1.x the team worked around this by introducing ng-src. The browser doesn’t recognize ng-src as the property that represents url to the image, so it leaves it alone. Angular can then, under the hood, write the actual “src” property once the binding can be resolved.

In Angular 1.x ng-src is not the only directive that does this, in fact there are many more: ng-blur, ng-click, ng-hide, ng-show, ng-disabled, ng-selected. All of these directives were made so Angular doesn’t get in the browsers way and vice versa. So for each property the browser has, a corresponding Angular directive exists.

Why is this so bad, let’s say for example that tomorrow all browsers include the following way to include HD images:

What does Angular 1.x have to do to make that work? Write a specialized directive of course! In an ideal world Angular would work with new HTML properties out of the box, without having to change Angular’s code.

In Angular 2.0 the core team decided to tackle this problem at the root. By making one unified syntax for all properties. That’s where the bracket and parenthesis come from. So looking at the following line of code again:

I would like to read this as: Create a property called “src” with the value of the expression, and update it whenever the value changes. The part between the brackets: “src” is just the name of the property Angular 2.0 must render on the HTML element.

So if “src-hd” was introduced tomorrow, I could write this in Angular 2.0:

The best part is that, unlike Angular 1.x, Angular 2.0 would not have to be updated itself. So Angular 2.0’s template syntax unifies all of the built in directives from Angular 1.x into one syntax.

Benefits of the new binding syntax

The first benefit as you have already read is that Angular 2.0’s template syntax is more future proof than Angular 1.x’s.

The new syntax is also easier to learn for beginners. If you already know HTML and you work as a web designer and suddenly you are dropped in an Angular 2.0 project, you simply need to learn to write square brackets around HTML properties you already know. There is no more need to learn al of these specific cases such as ng-src. The new syntax is simply closer to HTML than before.

Another benefit of the new syntax is that it is easier to reason about. What I mean by reasoning is that it is easier to understand a template just by reading it. For example what does “selected” do in this Angular 1.x directive?

It could mean one of the following things:

  1. It selects a certain marker based on the outcome of function “markers”.
  2. It is an event that executes a callback to “markers” whenever a marker is selected.
  3. The “selected” property is a two way binding that changes through the “markers” function.

In order to know which one of the above answers is correct you would have to read the definition of the google-map directive.

If this was an Angular 2.0 template:

Now it is immediately clear that “selected” is an event because of the parenthesis. You would not have to read all of the surrounding code to understand what something does.

Local Variables

Angular 2.0 templates brings us a new feature that was not previously seen in Angular 1.x. This feature is called local variables, it allows us to create variables that are only available in a specific template.

The reason for wanting to create variables that are only visible in your template is so you can create multiple templates for the same “controller”. Imagine if you had to make a page with a YouTube player component, that needs to work on mobile and desktop. You discover two great Web Components: one that works great on desktop and another that works great on mobile devices. So you create two templates: one for desktop and one for mobile. But now you might need two controllers, because you have two different youtube components, right? The answer is no, because Angular 2.0 allows you to create ‘variables’ directly in your template.

The syntax for creating a local variable is simply a name and a hashtag.

Lets look at an fictitious example of the mobile template:

Now take a look the desktop’s version of the template:

In both cases you can see we define a local variable called #player which we use to reference the ‘player’ HTML elements. In the play buttons we can then reference “player” in the (click) event to start a video. Note that the API to start a video is different between the desktop and mobile version. So even though the API is different we didn’t have to touch the controller at all, thats the power of local variables!

Templates

Angular 2.0 also introduces a new concept called ‘directive templates’, a directive template manipulates HTML. Lets look at an example:

If you know Angular 1.x you will find *ng-for familiar, it does what ng-repeat used to do. *ng-for manipulates the HTML by repeating the HTML element for N times.

Note that we create a local variable called #name that we reference inside of the <li> element. The #name variable is only available inside of the <li> element, because it is scoped to the template.

Another example of a template is *ng-if:

The reason this is called a ‘template’ is because behind the scene’s Angular 2.0 will convert the code to a <template> tag. So the *ng-for example would expand to:

A <template> element represents an inert piece of DOM that the browser will completely ignore. This gives frameworks such as Angular an easy way to define templates, without the browser trying to parse them and mess with them. The <template> element was basically created for use by JavaScript frameworks.

The benefits of the new *template syntax is that your IDE and text-editor can analyse these final <template> forms of the directive. This means that they can autocomplete your code and provide your with better help. This will ultimately make us developers that use Angular 2.0 more productive.

Codifying the new syntax

We can codify the new syntax as follows:

Property bindings []
Square brackets represent a property which has a binding to a value. This binding is always an expression. Angular evaluates it every time inside the run loop when it is dirty checking for changes. Whenever a change is detected the binding is updated.

The expressions should be  pure: each time they are evaluated with the same parameters they should return the same value. They should not cause side effects.

Events ()
Parenthesis represent events. Events handlers are statements, which cause side effects. The events always originate from actions taken by the user, such as: hovering the mouse or typing on the keyboard.

Variables #
Hashtags represent local variables. These are only available inside of the template where they are defined. They can be used so different templates for mobile and desktop can contain completely different pieces of code, but still keep the same controller.

Templates *
An asterisk represents a template with your HTML that is expanded to a <template> element behind the scenes. They were created so IDE’s and text editors can better autocomplete the code.

Conclusion

The new syntax makes it easier for newcomers to learn, because it more closely resembles HTML, and because you do not have to learn the built in templates. It also makes it easier to reason about templates so we can more easily discover what a template does.

Next week we will take a look at ES6, the new version of JavaScript, and how it affects Angular 2.0.

CORS with Spring MVC

In this blog post I will explain how to implement Cross-Origin Resource Sharing (CORS) on a Spring MVC backend.

Ebase Xi – Unsafe by Default – XXE

In my previous blog post I questioned the safety of the default configuration of Ebase Xi. I knew then that something was wrong as I had already found and reported two vulnerabilities to Ebase. But nothing happened. On the 6th of march, much to my surprise, I got an official Ebase security alert informing me that ‘All Ebase Servers are vulnerable to XXE attacks’. Which was one of the two issues I originally reported. Now that its public knowledge you can read this post for full details.

In-memory MongoDB for unit and integration tests

A few weeks ago I found myself having to fix a bug in a production system which uses MongoDB as its primary means of storage. As I was unfamiliar with the codebase, we had just taken over the project, the first thing you do is trying to find the test covering this functionality.

Jaw drop; no test in sight. What was the case, none of the interactions with the backing storage was under any form of testing. So it could happen that a simple aggregation query wasn’t returning the expected results

This was my first project in which I used MongoDB, coming from projects using HSQLDB to test the validity and outcome of queries, the first thing that flashed through my mind was in-memory MongoDB. The first hit on Google wasn’t promising http://stackoverflow.com/questions/10005697/does-mongo-db-have-an-in-memory-mode, but luckily some following results hit the jackpot.

CSRF / XSRF protection using Spring Security

The last few years there is an almost constant stream of news articles about some company leaking customer information one way or the other.
While not all of these leaks are caused by badly protected websites themselves, a lot are caused by misconfigurations in the web/data servers, programmers still have a hard time integrating some basic protection against attacks.

Ebase Xi Queries : Unsafe by Default

Ebase Xi (from ebasetech.com) 4.5.2 is a rapid application development platform I recently encountered at a client. The previous developers had left and a security audit revealed that the (many) forms they built with Ebase Xi were susceptible to SQL Injection. In this blog post I will tell how I fixed the SQL Injections and discovered some interesting things along the way.

The case for separating front- and back-end

At 42 we have an ongoing discussion about the separation of the front- and back-end of an application. The back-end being a RESTful service, and the front-end being a modern MVC JavaScript application written in AngularJS.

There are two camps within our ranks: the first camp believes the front- and back-end should be completely separated, where both applications have separate version control, build processes, and deployments.

The second camp believes that the back-end should provide the REST API, serve the JavaScript application, and that there should be one deployment and build process that delivers the whole application (front- and back-end) in one package.

Disclaimer: I’m in the camp that believes strongly in separating the two. So I want to argue the case for separating front- and back-end completely in the post.

Aggregations in MongoDB with Spring Data

Aggregations in MongoDB

The MongoDB aggregation operations allow us to process data records and return computed results. Aggregation operations group values from multiple documents together, we can perform a variety of operations on the grouped data to return a single result. Spring Data Mongo makes the usage of this feature from your Java application very easy.