Developing a MEAN app with Angular 2.0

I know, I know it is too early to be building end to end apps with Angular 2.0, but I got so excited after looking at ng2-express-starter by my dear friend Antonio Fernandes. I was like, If we can integrate an Angular 2.0 app with an Express app, we can definitely add the MongoDB layer to make it a M.E.A.N. app. So, in this post, we will be developing a MEAN Todo App (Grrr..). This post is heavily inspired by Antonio’s Angular 2.0 Express starter app.

The final app would look like

Screen Shot 2015-04-29 at 1.48.10 pm Screen Shot 2015-04-29 at 1.49.06 pm Screen Shot 2015-04-29 at 1.50.02 pm

You can play with a live instance of the above app here. (It might take upto a minute to load the page, please be patient or open the dev tools – network tab to check progress).

You can find the completed code here.

Couple of things before we proceed

  1. Thumbs up to Tim Jacobi for creating angular2-education repo, which consists of lot of useful links to learn Angular 2.0
  2. Angular 2.0 is still in development. The todo app we are going to build is developed using Angular 2.0 2.0.0-alpha. There is a very good chance that most or all of this code can be of no help when Angular 2.0 becomes stable.

Prerequisites

If you are new to Angular 2.0 check out

  1. Getting Started with Angular 2.0
  2. Tim Jacobi’s angular2-education repo

If you are new to MEAN Stack development check out

  1. MEAN Stack – A Hands on Tutorial (with Angular 1.x)
  2. MEAN Stack Workshop

Architecture

A MEAN stack app would typically consist of a server layer built with Nodejs & Express – Express being the web framework. MongoDB for data persistence & Angular as the client side MVW framework.

ng2As you can see from the above diagram, Express exposes REST End points that would be consumed by the Angular 2.0 app. And when any request is made to the REST end point, Express contacts MongoDB and manages the data.

This is pretty much our architecture.

Note : If you are looking for creating a secure REST API with Nodejs checkout : Architecting a Secure RESTful Node.js App.

Setting up the Server

First, we are going to setup an express app, build the REST API to Create, Read, Update & Delete todos and then integrate it with the Angular app.

Create a folder named ng2do-mean-app. Open a terminal/prompt here and run

npm init

Fill up the details as applicable.

Next, we will add express dependencies to our project. Run

npm install --save body-parser cookie-parser ejs express mongojs morgan path

This will download the required dependencies to run the express app. Once the above installation is done, your package.json should look like

At the root of the ng2do-mean-app create a file named server.js. Update it as below

This is a typical express server. Couple of things, on line 7, 8 we are including two sets of routes and on line 24, 25 we are mapping the routes to end points.

Next, we are going to create the routes folder and the two route files we declared above.

Create a new folder named routes at the root of ng2do-mean-app folder. Create a file named index.js inside the routes folder. And update index.js as below

We define a route to handle the http://localhost:3000/  and dispatch the index.html file.

Next, at the same level as index.js, create another file named todos.js. Update todos.js as below

Things to notice

Line 4 : I have created a new MongoDB instance for this example from MongoLab and configured it with Mongojs.

Line 7 : Endpoint to get all todos

Line 18 : Endpoint to get one todo based on the id provided

Line 31 : Endpoint to save a todo

Line 50 : Endpoint to update a todo

Line 79 : Endpoint to delete a todo

Test REST API

If you save all the file and run

node server.js

the express server would start on port 3000. If you navigate to  http://localhost:3000/api/v1/todos, you should be able to see all the todos (if any & if you have setup everything correctly). You can use Postman or any REST Client to test the remaining methods as well.

Pretty sweet right! Our REST API is completed. Now from our Angular 2.0 app, we are going to connect to the above REST API and manage our UI.

Setup the Client

The first thing we would be doing as part of the client side development is to download the Angular 2.0 starter app. This starter app consists of all the Angular 2.0 code and its dependencies.

From the root of ng2do-mean-app folder, run

git clone https://github.com/angular/quickstart.git public/vendor

As of today, the quickstart project does not ship with Angular 2.0 2.0.0-alpha source, which is needed for our project. To update the same, we will run the following commands from inside the public/vendor folder

npm install

gulp

npm install rx --save

The above steps are NEEDED till the quickstart project ships with Angular 2.0 2.0.0-alpha release.

Next, to manage client side dependencies, we are going to use bower. We will create a new bower.json file. From the project root, run

bower init

This will create a new bower.json file and it should look something like

Next, create a file at the same level as bower.json named .bowerrc. This file will consists of bower config. Update .bowerrc as below

Now, we will add Twitter Bootstrap to our app. Run

bower install bootstrap --save

This should download the Bootstrap source and place it inside the public/vendor/bower_components folder.

If you do remember, in routes/index.js we have a route that dispatches the index.html file. We will create that index.html file now.

Create a new folder named views at the root of our project & inside views create a new file named index.html. Update index.html as below.

Things to notice

Line 5 : We have included bootstrap css that we have downloaded using bower

Line 7 : The es6 shim file

Line 12 : Init our base component – todo-app

Line 18 : Paths where our assets are located

Line 28 : Kick off the app

In the next steps, we are going to create all the referenced files.

Client Side code structure

As of today, Angular 2.0 support only HTTP GET request using the XHR module. So, I have borrowed Antonio’s approach for making a HTTP GET, POST, PUT, DELETE calls.

So this is how we are going to structure the app

ng2-client

We will have a Todo App component, that will interact with the Todo Factory, which in turn uses the XHR factory to work with the REST API.

Developing the App

The first thing we are going to do is develop the todo-app component. Create a new folder named components inside the public folder. And create a new folder named todo-app inside the components folder.

Inside todo-app create a new file named todo-app.es6. Update todo-app.es6 as below

Things to notice

Line 1 : We import Component, View, bootstrap, For from Angular 2 source

Line 2 : We import TodoFactory, which we will be creating a bit later

Line 5 : We create a new component identified by the selector todo-app

Line 9 : We are going to load the template for this view from an external file and also specify what directives would be using, so that Angular can inject them.

Line 15 : We create a TodoAppComponent that consists of the component definition.

Line 17 : We create a new variable named todos  of type Array.

Line 19 : Inside the constructor method, we are going to fetch the list of todos using  TodoFactory.getAll() and assign the same to todos. This will take care of loading any existing todos on page load.

Line 27 : This method is used to add a new todo to our DB. When the user enters a Todo and hits the return key, we fetch the text, create a todo object and call the  TodoFactory.save() passing in the todo to be saved. Once we get a response, we update the local  todos with the response from the server, to keep things in sync.

Line 42 : This method is used to update the todo text in the DB. It is pretty much same as the addTodo() except, this time we have a _id  associate with the todo and we use TodoFactory.update() to update the data against the given todo.

Line 59 : This method is used to update the todo status, i.e. the todo completion. Here we pick the todo’s isCompleted property and build a todo object. We then call the same  TodoFactory.update() to update the data.

Line 74 : This method is used to delete a Todo. We pass the Id of the todo to be deleted to TodoFactory.delete() and the todo gets deleted from the DB. Once the server responds with a success, we clear the same from the local todos  array to save a DB call.

Line 91 : This is a utility method, that helps us manage the state of the todo. When clicked on the Edit button, next to the todo, we set isEditMode  to true and when we are done editing, we set isEditMode  to false.

Finally on line 101, we bootstrap the TodoAppComponent.

Next, we are going to create the template. Inside the todo-app folder, create another file named todo-app.html. Update todo-app.html as below

Before digging into the file, we will look at three changes to Angular 2.0 templating syntax.

  • Variable are declared using a hash before them – #name
  • Event Handlers are declared using a parenthesis around them – (click)
  • Property binding are done using square braces – [class]

Keeping the above in mind, we will go through the above template

Line 6 : We create a input element, which is bound to a local variable named todotext which is represented by  #todotext on the tag. We have bound a  (keyup) event that calls  addTodo() in our component definition.

Line 11 : If there are no todos, we show a message – No Todos yet!. This is achieved using  [hidden] property binding

Line 14 : We use the  *for syntax (analogous to ng-repeat) to iterate over all the todos in our collection and display them. Also do notice  [class.strike], (analogous to ng-class) if the current todo is in a completed state, we want to add a class named strike.

Line 16 : We provide a check box for the user to check or uncheck the todo. The state of the checkbox is maintained by  [checked]="todo.isCompleted". And when a user clicks on the checkbox, we set the value of isCompleted for that todo from updateStatus().

Line 19 : We display the todo text if it is not in edit mode

Line 20, 21 : we show the editable text box and a cancel button when the todo is in edit mode.

Line 24 : Button to toggle edit mode

Line 25 : Button to delete a todo

Now you can figure out what is happening on a tag based on the 3 new changes we saw earlier. Also, the classes which you see here are specific to Twitter Bootstrap.

That is it, our todo-app component is ready.

Now, we need to develop the two services. Create a new folder inside the public folder named services. Create a new file inside it named todos-factory.es6 and update it as below

Quite self explanatory.

Important : Angular 2.0 DOES NOT have a $http service. I have created one using the xhr-factory and named it to $http for familiarity sakes.

Next, create a new file named xhr-factory.es6 inside the public/services folder and update it as below

All we are doing is making a HTTP Request using the XMLHttpRequest() and returning a promise.

Pretty simple right! With this we are done with app logic. For some styling, we will create a new folder inside the public folder named css. Inside the css folder, create a new file named app.css and update it as below.

Test the App

That is it! Save all your files and run

node server.js

Next, navigate to  http://localhost:3000 and you should see

Screen Shot 2015-04-29 at 1.48.10 pm

Add a few todos and you can click on edit

Screen Shot 2015-04-29 at 1.49.06 pm

You can mark todos as completed or delete them

Screen Shot 2015-04-29 at 1.50.02 pm

Simple and sweet MEAN App with Angular 2.0


Thanks for reading! Do comment.
@arvindr21

 

Getting Started with Angular 2.0

Recently Angularjs team has launched a 5 mins quick start tutorial on getting started with Angular 2.0. I have taken the same tutorial (with minor changes) and explained it below. There are a lot of blanks to be filled, but this is my first attempt at Angular 2.0.

You can find the source code for the Hello World app built in this post here.

So, let us get started with NG2.0.

What is Angular 2.0?

AngularJS 2 is a framework for mobile apps.  It is for desktop as well, but mobile is the hard bit that we will get right first.  The AngularJS you know and, hopefully, love will still be there with data-binding, extensible HTML, and a focus on testability.

You can read more about Angular 2.0 and its proposed features from here.

5min Tutorial by Angular Team

Angular team has released a tutorial on how to get started, where they explain how to setup the project and run a simple Hello World example.

We will follow the same here. The tutorial they have provided is quite self explanatory with some “Googling”.

To get started, create a new folder named ng2 and open a new terminal/prompt here.

Make sure you have Git installed, and run

git clone https://github.com/angular/quickstart.git hello2ng2

This will clone the quick start project to hello2ng2 folder.

The project consists of the following libs (as of today)

  • Pre-built ES5 version of Angular 2 alpha-11
  • Pre-built ES5 version of rtts-assert alpha-6
  • The es6-shim, which includes Traceur, ES6 Module Loader, System, Zone, and Traceur options for meta-data annotations.

Do notice the directory structure

At the root of the directory you have a Gulpfile that consist of simple build tasks to download Angular 2.0 and its dependencies using the ng2build.sh.

To try this out, you need to have Nodejs installed. And Gulp should be installed globally. To install Gulp globally, run

npm install -g gulp

And then, We will install the dependencies for this project. Run

npm install

Now to regenerate Angular and its dependencies, run

gulp

And you can see the dependencies being removed and added again. This is incase you have messed up anything while going through the source code of Angular2.

EcmaScript 6

Before we go further, I would recommend having a knowledge of EcmaScript 6. One of the resource that helped me get started was es6features repo. Simple and lucid explanations of ES6 features.

This knowledge is quite essential as Angular 2.0 is written for ES6 and to support ES5. When we build the Hello World Example, I will point you to the required resources.

Build the App

The Angular tutorial suggests to create the project related files at the root of the directory. With so much going on at the root of the directory, I found it easy to maintain the files inside a folder named app. This situation is temporary till Angular 2.0 moves to a stable release.

So, create a new folder named app at the root of the project. Create a file named index.html inside the app folder. And update it as below

Things to notice

Line 5 : We load up the es6-shim.js from the dist folder to work with ES6 in current browsers.

Line 10 : We created a new component named my-app. We will talk about components soon.

Line 13 : ES6 comes with Modules and Module Loaders. This makes on demand importing very easy. If you have used Requirejs or the Commonjs module system while working with Nodejs, this will look very familiar.

Line 14 : We refer Angular 2.0

Line 15 : We refer Runtime assertions library

Line 16 : We load a file named app.es6 that we will be creating next. This file will consist the definition for  <my-app></my-app>.

Line 20 : We kick off the app.

Next, create a new file named app.es6. The es6 extension indicates that you are loading a file with EcmaScript 6 syntax. (This is more for your text editor to show syntax highlighting. You can js extension as well if you feel that too much is changing).

Update app.es6 file as below

I was overwhelmed as well as confused when I first saw the code. Learning Angular 2.0 is a challenge in itself and adding ES6 touch to that makes this a bit tricky.

Let’s see what we have in this file

Line 1 : If you have already gone through the modules feature, you should understand this syntax. All we are doing here is importing the required components from angular2 to be used in the current file.

Line 4 : The “@” is an annotation. Angular 2.0 uses a library called AtScript (@ script). 

AtScript

JavaScript, the de facto language of the browser, has a large, thriving community. However, it is missing some features which would make it much more manageable for large-scale application development. The goal of AtScript is to enhance the language with these missing features without infringing upon its current capabilities.

You can read more about it : AtScript Primer. As far as I have understood (I could be totally wrong here), AtScript simplifies the syntax of ES6 in its own way. Taking an example from the primer

ES6

AtScript

You can read more about ES6 classes for better clarity.

Though Angular team does not force the users to use AtScript, but it definitely looks like an advantage working with it.

Getting back, As per the docs, Angular 2 works with a concept of components. And a component consist of 2 parts

  1. The Annotation Section – This consist of the meta data (component selector, template) for that component
  2. The Component Controller Section – This is a ES6 Class, from which the template would be reading the properties that are interpolated ({{…}}) inside it .

So, (referring to app.es6)

Line 5 : Identify the selector on page that would be the base for our component

Line 8 : The template to be injected. Notice  {{ name }}

Line 14 : Declare the values to be used in the template. In our case it is World!

And finally on line 19, we bootstrap the component. As per my understanding, this is similar to exporting the main object from this file (analogous to module.exports) but instantiating it before exporting.

That is all we need to build a Hello World app using Angular 2.0.

Launch and test the App

You can use any static server to launch the app. If you have python already installed, you can run

Windows *nix
python -m http.server    python -m SimpleHTTPServer

from inside the hello2ng2 folder or you can use a node module named http-server to do the same. You can install the same using the below command

npm install http-server -g

And then you can launch the static server by running

http-server

from inside the hello2ng2 folder. And then navigate to  http://localhost:8080/app/ you should see

Screen Shot 2015-03-23 at 11.37.56

Next Steps

There are quite a lot of things going on with Angular 2.0 and I think it would take another 3 – 4 months to get a fair idea on where Angular 2.0 is headed to.

You can track the progress here and Angular 2.0 milestones here.

You can also checkout the resources page, which has a few but helpful links on Angular 2.0.


Thanks for reading! Do comment.
@arvindr21