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

 

M.E.A.N. Stack Development with Vagrant

If you are new to MEAN, I would recommend checking out my MEAN Workshop.

Also checkout my tutorial MEAN stack – A Hands on Tutorial

Recently I started using Vagrant for one of my clients. The requirement was to have a unified working environment for all the developers, so that they can focus more on code and less on the onboarding and setup. So, I built a Vagrant box that is ready to be used for M.E.A.N. Stack development.

If you are new to Vagrant take a look at

In this post, I will show how to consume the mean-box I have created as is and get started with M.E.A.N. development. Later in the post, I will also show how you can build a customized version of your own Vagrant box and then share it with your team.

So, let us get started.

Continue reading

Re-Architecting a Firebase app to work with Node.js and MongoDB

In the last few days, I have see people worrying about two major problems. One of which is what is going to happen when Angular 2.0 releases and next one is how to migrate an existing Firebase code to a Node.js/MongoDB platform.

I am not going to answer problem one, as I don’t know what is going to happen (ahem chaos) but I will try and propose an experimental solution to the second issue on how you can re-architecting a Firebase app to work with Node.js and MongoDB.

I have met a few people who used Firebase to develop their product and hit the market in a short span of time. Now that the product is doing good, they want to stabilize it further and add more features. And they have realized that a few things may not be that easy to achieve using Firebase.

So they have built another layer with Node.js and MongoDB which kind-of replicates the data and performs actions on it. Another solution I have seen is to use apibase – a Node.js module to communicate with Firebase. I was not really satisfied with the solutions.

So, I went back and asked why Firebase and why are you fitting Firebase in your application architecture? Here are 2 major answers

  • Real time data sync
  • Offline storage

After giving the above reasons a good thought, I have come up with the below architecture that will “emulate” Firebase using Websockets and Local Storage inside a Node.js/MongoD.

If this solution gets stable over a period of time, I may create a yeoman/slush generator to scaffold a Node.js/Express.js and a MongoDB app with real time data sync and offline storage capabilities.

For this post, I will use a simple Todo app as an example. You can find the completed code here.

So let us get architecting!

Continue reading

Node Webkit, Firebase and Ionic Framework – A one to one chat client

A few days ago Pooja Pasupu reached out to me after reading one of my articles on Node webkit named Building a Chat App with node-webkit, Firebase, and AngularJS. In the above article I have shown how to create a desktop based group chat client using Node webkit and Firebase. She wanted to know if we can build a desktop application for one to one chatting like Google talk or Yahoo messenger using node webkit. And this post is a response to that query.

In this post, we are going to build a desktop application that is like your typical one to one chat client. Where, a user logs in, sees a list of other users. And can chat with any of them. This app is called Chatter.

Below is a quick demo of the completed app.

PS : I have opened 2 clients on the same machine to demo the application.

As you can see from the above demo, we have used Firebase as our data store to manage the user’s presence and their chat messages. And also, if you did notice, when User B sent a new message to User A, a new chat window opened automatically, like a typical chat app.

We will take a look at how all the above can be achieved. So, let us get started on building Chatter.

You can find the completed code here.

Continue reading

Raspberry Pi, Camera and Node.js – Live Streaming with Websockets #IoT

A few days ago Bala Kolluru has reached out to me asking if we can control a Raspberry Pi camera module using Web browser, so he can view a live stream from any HTML5 powered device. I was intrigued by this idea and wanted to give it a try.

In this post, we will see how we can implement a system that can “stream” a video from our pi to a browser. The completed system would look like

Pretty sweet right! I am able to see my aquarium from any where and check on my only gold fish. This can be extended to do anything.

For instance, you can hook the camera up pointing at the front door, as soon as someone rings the bell, you can see who is at the door by opening the video stream URL in your mobile/tablet/computer and confirm if you need to wear pants to open the door.

So let us see how we can build such an awesome multi-purpose system.

You can find the complete code for this system here.

Continue reading

Node-Webkit File Player – A File player for your desktop

A few days ago, Ignacio Tartavull reached out to me mentioning that he had built a file viewer based on Node Webkit powered Dashboard application and associated the node webkit app as the default opener for.ipynb files. Which I thought was a pretty genius idea. You can check out the INotebook app here.

Inspired by that idea, I have written a file browser/player app with node webkit that can “play” basic files like txt, log, json, md, mp3, mp4, png and jpeg.

Also, mustapha has reached out to me requesting another tutorial on Node webkit. And Mitesh Agarwal reached out to me requesting a post on a node webkit file viewer. So here it goes.

The final product we are going to build will look like

You can find the completed code here.

So, let us get started.

Continue reading

Ionic, Twilio and Node Scheduler – A Reminder App – Part I [Server]

Ionic, Twilio and Node Scheduler – A Reminder App – Part I [Server]

In this post, we will take a look at building a Reminder app. With this mobile hybrid app, a user can register, login and then create a reminder. While creating the reminder, the user has an option to schedule a Call or a SMS to remind him/her of the task at the scheduled time. Sweet right?

Our client will be built using Ionic Framework and our server side will be built on top of Node.js with Express.js as the framework. We will be leveraging a node module named node-schedule to schedule tasks. And we will be using the powerful cloud based communication API exposed by Twilio to make a call or send an SMS.

Below is a video recording of the app. There is no audio, but you can find the recorded phone call after that

Note : There is ~25 seconds gap between scheduling the call and the call arriving. The call start @ 01.06 mins into the video.

Screenshot_2014-09-29-23-51-47 Screenshot_2014-09-29-23-53-15 Screenshot_2014-09-29-23-54-00

You can find the completed code here.

This post is going to be the first half of the tutorial, where we would be working on the server side to build the REST API with which our Ionic app would consume to register, authenticate users and manage reminders.

For the Ionic app take a look : Ionic, Twilio and Node Scheduler – A Reminder App – Part II [Client]

So, Let us get started.

Continue reading

Ionic, Twilio and Node Scheduler – A Reminder App – Part II [Client]

Ionic, Twilio and Node Scheduler – A Reminder App – Part II [Client]

This is the second part of the two part post on how to build a reminder app using Node scheduler, Twilio cloud API and Ionic Framework. If you did not already check out the first part, you can do so here : Ionic, Twilio and Node Scheduler – A Reminder App – Part I [Server].

To give a quick overview, we have gone through the required technologies, understood the architecture and how each component plugs into another. Then we have gone ahead and built the REST API using Node.js.

In this post, we will continue our journey toward the app. Quick reminder, this is where we are headed to!

Note : There is ~25 seconds gap between scheduling the call and the call arriving. The call start @ 01.06 mins into the video.

 

You can find the completed code here.

So, let us continue development.

Continue reading

Architecting a Secure RESTful Node.js app

Architecting a Secure RESTful Node.js app

In this post, we will take a look at architecting a Node.js app that will act as a REST API server for all of our clients. We will be implementing a Token Based Authentication to authenticate and authorize the client to access the application data.

This application design is targeted at systems that would like to implement its own REST API with a custom authentication. To showcase how one can consume the REST API with authentication, we will be writing an Angular.js client.

This post is inspired by Authentication with AngularJS and a Node.js REST api.

You can find the completed code here.

So, let us get started. Continue reading

Twilio, Ionic Framework and Node.js – A Message & Call App

Twilio, Ionic Framework and Node.js – A Message & Call App

Also checkout Ionic Restify MongoDB – An End to End Hybrid App, Ionic Framework, Angularjs & PhoneGap Build- The Awesome Threesome! and Architecting a Secure RESTful Node.js app

In this post, we will take a look at integrating Twilio, Ionic Framework and Node.js to build a Mobile Hybrid app named “The Twilio App“.  This app can send SMS or trigger calls using the Twilio cloud based API’s. We will be using Ionic Framework as our Mobile Hybrid app framework and Node.js/Express.js as our REST Server to customize the responses. We will also use DiskDB to keep a track of our API calls.

The final app would look like Screenshot_2014-09-14-18-34-16

Screenshot_2014-09-14-18-37-33Screenshot_2014-09-14-18-38-21 Screenshot_2014-09-14-18-39-03

And the call you get would sound like

 

You can find the complete code here.

So let us get started.

Continue reading