How to execute Angular2 code before any rendering

Sometimes, in a single page application, we need to execute some code before any rendering. For exemple, before the execution of your code, you may need to send an HTTP request to fetch some configuration from your server. How can we implement this kind of behavior in Angular2… with a provider.

The framework give you access to the token APP_INITIALIZER. This token is defined in the application_init.ts file (https://github.com/angular/angular/blob/master/modules/@angular/core/src/application_init.ts).

export const APP_INITIALIZER: any = new OpaqueToken('Application Initializer');

In order to know how to use this token, we can have a look to the ApplicationInitStatus service defined in the same file.

constructor(@Inject(APP_INITIALIZER) @Optional() appInits: (() => any)[]) {
}

The constructor of this service will inject the APP_INITIALIZER token, and its value is an array of functions. These functions can execute synchronous or asynchronous code. For asynchronous task, these functions should return the Promise object, in order to let the framework know when all promises are resolved.

As an example, I will create a ConfigService service, that will be executed during the initialization of the application, and we will set the result of an HTTP call to a config property.

First, the next snippet is the implementation of the ConfigService service :

@Injectable()
export class ConfigService {

    private _config: any;

    constructor(private http: Http){}

    load(): Promise<any>{
        return this.http.get('/api/config')
              .map( (response: Response) => response.json())
              .toPromise()
              .then(data => {
                  this._config = data;
                  return data;
               })
    }
    
    get config(): any {
        return this._config;
    }
}

Next, you need to define a provider for this service, and add the call to the load method to the APP_INITIALIZER token. Do not forget the multi parameter. As this token is an array of function, this pararmeter is mandatory for appending a new value to this array.

@NgModule({
  providers: [
    ConfigService,
    {
      provide: APP_INITIALIZER,
      useFactory: (configService: ConfigService) => function() {return configService.load()},
      deps: [ConfigService],
      multi: true
    }]
})
export class ApplicationModule { }

How to avoid hosting issue with AngularJS et TypeScript

This a very quick article about an issue I had fews days ago. I gave some trainings about how to prepare your AngularJS application to Angular2. This training is based on three steps : - Use AngularJS coding rules - Use TypeScript - And finally migrate the TypeScript application to Angular2.

But with TypeScript, I had a simple issue and I spent fews minutes to find the solution. Here is the code :

angular.module('myModule').controller('MyController', MyController)
class MyController {

}

What is your first impression of this code ? It should work. I think… but in fact if you copy/past this snippet in your TypeScript application, you will have a small JavaScript exception.

The magic come from the hoisting behavior. With this behavior, all variable definition are moved, at runtime, at the top of the execution stack. For example, the definition of the hoist variabe is moved at the very beginning of the foo function.

//In your code
function foo(){
  if(true){
    var hoist = true;
  }
}

//At runtime
function foo(){
  var hoist;
  if(true){
    hoist = true;
  }
}

And this is exactly the same behavior I have with my TypeScript code. If you copy/paste my code into the online TypeScript compiler, you will get this result

angular.module('myModule').controller('MyControlller', MyControlller);
var MyController = (function () {
    function MyController() {
    }
    return MyControlller;
}());

And if you follow the same process as the one explained previously, at runtime, the previous code is replaced by the following one :

var MyController;
angular.module('myModule').controller('MyControlller', MyControlller);
MyController = (function () {
    function MyControlller() {
    }
    return MyControlller;
}());

So at runtime, we add our controller to the AngularJS configuration, but the myController variable is in fact undefined, and not the function returned by the IIFE function.

To solve this issue, you just have to move the register of the component at the very end of your file :

class MyController {

}
angular.module('myModule').controller('MyController', MyController)

Accessing static attribute values in Angular 2

A quick article in order to explain one simple Angular2 decorator. If you don’t know anything about decorators, you should read the article written by Pascal Precht on this topic (and you should read all articles of this blog in fact ;)).

The decorator I would like to present is @Attribute(). The decorator has to be used with a parameter of a component’s or Directive’s constructor.

import {Directive, Attribute} from 'angular2/angular2'

@Directive({selector: 'input'})
class Component {
   constructor(@Attribute('attributeName') public param:String){
   		
   }
}

Thanks to this decorator, you are able to retrieve the constant value of an attribute available in the host element of this component. One use case I had in mind when writing this article, is the support of the new HTML5 input types. For browsers that do not support this new input types, and only for these browsers, I would like to use polyfills, like jQuery datepicker for date input.

The name of the annotated parameter should be named exactely the name of the attribute you want to retrieve.

import {Directive, Attribute} from 'angular2/angular2'

@Directive({selector: 'input'})
class DateDirective {
   constructor(@Attribute('type') private type:String, private element:ElementRef){
		if(type === 'date' && myBrowserDoesNotSupportDateInput()) {
		   //Call datepicker jQuery widget on the element.nativeElement attribute
		}   		
   }
}

Of course, this sample is in fact not the best implementation. Because thanks to the @Directive’s selector property, we can directly select date input with this value : input[type=’date’]

How to enable CSP on App Engine

In this article, we won’t talk about the Content Seccurity Policy (CSP). You already have a lot of awesome documentations, blog posts about this W3C recommendation. The one I prefer is the article written by Mike West on the (also amazing) HTML5Rocks website.

Just to summarize, CSP is a W3C recommendation, that provides a new standard HTTP header (Content-Security-Policy), used to list all resources that browsers is allowed to download on that page. This header is used to prevent cross-site scripting attacks.

In my simple Google Application, I have added this useful header in order to make my “not-yet” awesome application more secure. As you already had a look to my previous post, you are already aware of my Angular 2 application. I have to import JavaScript scripts from

  • the same domain (for my application scripts)
  • code.angularjs.org (for AngularJS)
  • jsmp.io (for SystemJS)
  • github.jspm.io (for Traceur-runtime)

In the AppEngine Yaml configuration file, I will add this new HTTP header for the URL matching my index.html file :

- url: /
  static_files: static/index.html
  upload: static/index.html
  expiration: "15m"
  http_headers:
    Content-Security-Policy: "script-src 'self' code.angularjs.org jspm.io github.jspm.io;'"

The self placeholder stands for all JavaScript files hosted on the same domain of your application. Once you have added this header, your browser will warn you if you try to download a JavaScript file from a different domain.

In fact, If you launch my Angular2 application with this configuration, it won’t work anymore for two reasons.

  • First, in our index.html file, we ask SystemJS to import our app component. But by default all inline JavaScript are disabled by the CSP recommendation. You have to enable it with the unsafe-inline placeholder.
  • Secondly, I think AngularJS use the JavaScript eval method, also disabled by default, for security reason. You have to enable it thanks to the unsafe-eval placeholder.

At the end, your CSP configuration should look like :

- url: /
  static_files: static/index.html
  upload: static/index.html
  expiration: "15m"
  http_headers:
    Content-Security-Policy: "script-src 'self' 'unsafe-inline' 'unsafe-eval' code.angularjs.org jspm.io github.jspm.io;'"

For the purpose of this post, I have only configured CSP for JavaScript scripts, but you can of course limit CSS files, images, … downloaded by the browser.

The ESLint plugin for AngularJS is ready for Angular2

Angular2 is the next version of the amazing JavaScript framework we use since few year. As this version is quiet different from the first version, the eslint-plugin-angular, available on NPM, should give the possilibility to create rules for the first or second version. And, in fact, it is very easy to do, and it is actually already usable.

We just need to add a new property in the global ESLint settings object we can define in the configuration file of this tool. For the eslint-plugin-angular, I have decided to create an… angular property, that can have two values : 1 (for Angular 1) or 2 (for Angular 2)

plugins:
  - angular

rules:
    angular/ng_controller_name:
      - 2
      - '/[A-Z].*Controller$/'

globals:
    angular: true

settings:
    angular: 2

Once this value defined, we can have access to this property in our rule. We just need to read the value of the context object, defined as a parameter of the module, in which the the rule is defined :

module.exports = function(context) {

  'use strict';

  //We disabled this rule for Angular2-based application
  if(context.settings.angular === 2){
    return {};
  }

  return {

    'CallExpression': function(node) {
    }
  }
}

How to configure App Engine for your Go application

A new blog post since a long long… very long time. I promise I will write articles more often than in the past. For this rebirth, I will start with the first article of a serie about Google technologies.

I have started last week a project in which I will only use Google technologies. It will help myself to learn new stuff. I won’t explain what this application will be used for, I will let you discover with these blog posts.

What I have in mind for the moment, is an application using :

  • The Go language for the server-side hosted on App Engine
  • Angular2 and Material Design Lite for the front-end

If you have other ideas for the technical stack, do not hesitate to comment one of my posts, or create issues on the Github repository. I will be very glad to have a look to your ideas, and write some articles about them.

In a daily bases, I am working with front-end technologies (HTML5, AngularJS, jQuery, …). All articles I will write about server-side components will be maybe too simple for some of you. I am sorry for that. But the main goal of this serie of posts is the discover of Google products.

Let start with the beginning… with the quick configuration of my App Engine instance, defined in a app.yaml file.

The application will be composed of two parts : an REST API (implemented in Go) and an interface (using Angular2). The UI part should be available at “/” and the API at “/api/”. In the app.yaml configuration file of App Engine, I have to configure differents handlers, in a handler block, based on an URL pattern.

Here is the basic version of this file, defining the technology of the application hosted on App Engine.

application: xxxxxxx
version: 1
runtime: go
api_version: go1

handlers:
#handlers

Here is the description of these properties :

  • application : the ID of the application you have created on App Engine
  • version : the version of your application
  • runtime : the App Engine runtime needed for your application
  • app_version : the version of the runtime

The first handler we will define is for the REST API. We have to define two properties :

  • url : the pattern of the URL. In this regular expression, you can define capture group (more informations about these groups later).
  • script : the name of the script App Engine has to execute for this URL pattern. For Go application, you have to use the magic string _go_app.
handlers:
- url: /api/.*
  script: _go_app

When your API is implemented, if you launch your application with the goapp utility (maybe a specific article about this command line tool ?), your API should be available !

So we have our API, let’s configure our static files (CSS, JS and HTML for the moment). We will define the same kind of configuration described previously.

For each URL pattern (based on the file extension) , we will define at least three properties :

  • mime_types : the mime-type of the corresponding static file
  • static_files : the path of the files matched by the URL pattern. You can access to capture groups defined in the URL pattern (“\1” refer to the first group, “\2” the second one…).
  • upload : a regexp corresponding to the path of all files served by this handler

Other configuration properties are available, I let you read the corresponding documentation.

handlers:
- url: /(.*\.css)
  mime_type: text/css
  static_files: static/\1
  upload: static/(.*\.css)

- url: /(.*\.js)
  mime_type: text/javascript
  static_files: static/\1
  upload: static/(.*\.js)

- url: /(.*\.html)
  mime_type: text/html
  static_files: static/\1
  upload: static/(.*\.html)

- url: /
  static_files: static/index.html
  upload: static/index.html

Of course, this small configuration is not enough. You should add for every static files your App Engine instance has to serve, the corresponding configuration block (XML, font, …). You can have a look to the file I have created for the application here.

And this first post is now drawing to a close. You should have now an up-and-running application you can deploy on App Engine.

See you soon…

Récupérer le nom du fichier JavaScript dans vos règles ESLint

Si vous avez lu d’autres articles de ce blog, vous vous doutez que j’aime beaucoup l’outil ESLint qui permet de vérifier la qualité de votre code JavaScript. Le gros avantage de cet outil, si nous le comparons à JSHint ou JSLint, c’est le fait de pouvoir créer très facilement de nouvelles règles, liées à votre application, vos technologies, vos équipes, …

Voici une petite astuce que j’ai découvert la semaine dernière. Si vous voulez exécuter une règle en fonction du fichier en cours, vous allez pouvoir récupérer le nom de ce fichier grâce à l’objet context disponible dans votre module. Pour rappel, une règle ESLint correspond à un module défini dans un fichier.

Dans l’exemple ci-dessous, le paramètre context sera valorisé automatiquement par ESLint. Il possède une méthode très intéressante : getFilename(); qui, comme son nom l’indique, retournera le nom du fichier.

module.exports = function(context) {
        
    "use strict";

    return {

        "CallExpression": function(node) {
                if(context.getFilename() === "protractor.js"){

                } else {

                }
            
        }
    };

};

Récupérer la configuration Protractor dans vos tests

Un petit article pour partager une petite astuce que je viens d’utiliser pour l’un de mes projets.

Comme la plupart d’entre vous ;), j’utilise bien sûr Protractor pour tester mes application AngularJS. Dans l’une de mes applications, j’avais besoins de récupérer la propriété baseUrl définie dans le fichier de configuration Protractor, afin de l’utiliser dans mes tests.

Rien de plus simple… Comme le fichier de configuration Protractor est un Module (exportant un objet config), il est dont possible d’importer ce module, et d’aller récupérer le ou les propriétés que vous avez besoin :

(function(){
	'use strict';

	var conf = require('../protractor.conf.js');
	
	console.log(conf.config.baseUrl);

	describe('Home Page ', function() {

		beforeEach(function () {
			browser.get('/#/');
		});
	});
})();

Utiliser ESLint directement dans Sublime Text 3

Bonjour à tous.

J’ai passé quelques heures hier soir sur ce sujet, et c’est donc pour cela que je partage cette petite astuce.

Si vous êtes, comme moi, un grand fan de ESLint, l’outil pour vérifier la qualité de votre code JavaScript, ce petit article va sûrement vous être très utile.

Il existe un package dans Sublime Text, SublimeLinter, qui permet de vérifier la qualité de votre code. A ce package s’ajoutent de nombreux plugins que vous devez utiliser en fonction du type d’applications vous êtes en train de développer : JavaScript, CoffeeScript, PHP, … Pour le JavaScript, je ne peux que conseiller SublimeLinter-eslint qui permet d’intégrer notre plugin préféré à Sublime Text.

Afin d’avoir la même configuration ESLint pour tous mes projets, j’étais à la recherche d’un moyen d’utiliser le paramètre ‘–config’ disponible dans ESLint.

Grâce au plugin SublimeLinter, il est possible d’ajouter des paramètres à la ligne de commande exécutée. Cette configuration doit être définie dans le fichier Settings de SublimeLinter. Il suffit d’utiliser l’option ‘args’ pour le linter ‘eslint’.

Sublime Text Menu

Sublime Text Configuration

Jug Summer Camp 2014

Mieux vaut tard que jamais…

J’ai eu la chance de participer au Jug Summer Camp en septembre 2014, à La Rochelle. Un grand merci à l’organisation, et, je l’espère, rendez-vous à l’année prochaine.

Ce fût également l’occasion de faire ma première conférence (un simple quicky), dont le sujet était ESLint, une librairie Node.JS pour vérifier la qualité de votre code JavaScript.

Jug Summer Camp 2014 - ESLint from Demey Emmanuel