Setup Angular 2 Nodejs Structure – Angular CLI – Express

Angular 2 js is finally released after rolling up from all development phases, Alpha, Beta and release candidates. And Now we can code with the stable version. I was frequently going through Angular 2 and has worked with all previous version of Angular Beta and Release Candidate updates with some of my demo project ready. As Angular 2 is finally released, one of my Client asked me to start up an ecommerce based project with Angular 2 and nodejs. As I am soon going to initialize the project work, the first basic step for me to know about about how to integrate and setup Angular 2 Nodejs project structure and to make client Angular communicate with Server Nodejs Setup.

Setup Angular 2 Nodejs Structure - Angular CLI - Express
Setup Angular 2 Nodejs Structure – Angular CLI – Express

I used to play with Angular 2 code in my free time to create some demo, which also excites me to share my Angular 2 code with my team. As Angular 2 is very new and my team used to code with Angularjs 1 which is quite different to Angular 2, I engaged myself and two more coders of my team full time to work on this (angular 2 nodejs ecommerce based) project, so that me and both of my coders can learn, understand and accomplish the project within time constraint maintaining quality.

Lets give me a try to explain you how we can setup Angular 2 Nodejs Structure. Before getting into project structure, I am assuming that you would be aware of Angular 2 basics(components, routes, services, etc) and Nodejs (I am using Express Framework here).

prerequisites:

If you have not installed Angular CLI then you need to install it before going through this tutorial i.e by running


npm install -g angular-cli

OR

npm install -g angular-cli@latest

Note: Both the Angular CLI and generated project have dependencies that require Node 4 or higher, together with NPM 3 or higher.

Setup Angular 2 Nodejs Structure – Angular CLI – Express

Lets first create a Project folder at your desired location i.e I am creating folder name as nodejs-angular2-setup 


mkdir nodejs-angular2-setup

Make a directory, lets called it as client inside your project folder i.e nodejs-angular2-setup, where we are going to store all angular 2 code. You don’t need to use mkdir command, instead we can use Angular CLI to create a client generated code i.e


ng new client

Make sure you have already installed angular cli latest version. Now lets navigate to client and run and build angular 2 code i.e


cd client

ng build

ng serve 

You may check the output of Angular 2 code at http://localhost:4200. This way your client Angular 2 setup work is completed.

Secondly, also check if you can see generated files in dist folder inside client directory (this files were generated by ng build command). Now we are going to use this generated ‘dist folder’ and render this angular generated html javascript over nodejs port. Dist folder contains combined bundle html and javascript file which is finally used as your client data.

Coming back to parent folder i.e node-angular2-setup in your command line console to create a structure for server nodejs.

Lets first create a directory called as server inside main project and navigate to server directory.

Lets run init command, which would create a package.json file i.e


npm init

And provide input as required i.e Name, version, description etc for app as can be seen in the image provided below.

Setup Angular 2 Nodejs Structure - Angular CLI - Express
Setup Angular 2 Nodejs Structure – Angular CLI – Express

In the console, check if you are at server folder, and type in to install and initialize express.


npm install express --save

Now lets create a file app.js insider server and paste in following code.


var express = require('express');
var app = express();
var path = require('path');

app.use('/',express.static(__dirname+'/../client/dist'));

app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname+'/../client/dist','index.html'))
});

app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

app.listen(3000, function () {
console.log('Example listening on port 3000!');
});

module.exports = app; 

Finally your app structure would look like this:

Setup Angular 2 Nodejs Structure - Angular CLI - Express
Setup Angular 2 Nodejs Structure – Angular CLI – Express

You might be aware of the above code. We are just asking nodejs to serve static content from the dist folder of client i.e generated by angular 2. In this way when we will start the node express application, angular 2 code should serve the html and javascript content.

Finally start the server, and check if angular2 code is served on port 3000 (you may change the port number by defining in app.js). For starting nodejs server, just navigate to project home directory, and run following command from console.


node server/app.js

If you enjoyed and understand the article do share this post with your friends and collegaes. Also Do subscribe this blog to get the latest updated version of all upcoming post of Angular 2 js and nodjes.

Debug JavaScript code – Google chrome debugger help you

Debug JavaScript code with Google chrome. Debugging is a process of finding and reducing the number of bugs of your programs. As web developer are very much engaged coding with JavaScript, they need to frequently debug the code when the desired output does not comes. JavaScript code can be debugged easily in chrome or other browsers like internet explorer, Mozilla Firefox and many other list of browsers that are made just to debug JavaScript code. Google chrome provides this feature of debugging JavaScript code, and i used to explore bugs mostly in chrome only.

From here you can start over. Firstly install google chrome, and run your web app in chrome, which you want to debug. You can run the debugger, by selecting, options -> tools -> JavaScript console as seen in figure below:

Debug JavaScript code
Open debugger : Debug JavaScript code

Script tab will be opened. Usually, in the right side of the opened tab, you can see some of the important buttons to use debugger efficiently, whose description along with the image is given below:

Debug JavaScript code with Google chrome
Debug JavaScript code with Google chrome

Debug JavaScript code :

Here is the explanation of all buttons whose respective numbers are marked in the figure:

1. ) Play and pause : It is used if you want to debug the code or not.
2.) Step over : This button will make you jump step by step in your javascipt code
3.) Step into : This will cause the debugger to move its execution to the first line in the functions definition.
4.) Step out : This will cause debugger to move its execution to the parent function.
5.) deactivate breakpoints: This will remove all the breakpoints you have marked in the code.
6.) Breakpoints : Just put the cursor to the left of the code and the breakpoints will be marked.

Let me demonstrate you to debug very simple code given below. Here i had introduced an error, i.e written document.wrte instead of document.write in the code given below to print “Take care”. Here is the code. I have marked the error with the underline.:

Debug JavaScript code with Google chrome

<html>
<head>
<script type = “text/javascript”>
function call(){
document.write(‘Hello World!’);
document.wrte(‘Take care’);
}
</script>
</head>
<body>
Hello world
Call funtion : <input type=“button” value =“submit” onclick=“call()”>
This is my way.
</body>
</html>

Run the web page. Now to debug the code, open javascript console as described above, and see the error after pushing submit button.

Output of Debug JavaScript code with Google chrome

debug javascipt code with google chrome
Output : debug JavaScript code

It will indicate, that html document has no method wrte. Great, we caught the error, now modify the code, i.e instead of wrte correct it to write. Now run the code and jump to JavaScript console, your code is correct, no JavaScript error is found, as can be seen below:

debug javascipt code with google chrome
Ouput after correcting: debug JavaScript code

In the demo above, i have not used breakpoints, while you can mark breakpoints and debug it step by step with the tools provided in Google chrome.

Load Dynamically JavaScript file in AngularJs with RequireJs

Load Dynamically JavaScript file in AngularJs with RequireJs . If you are creating larger scale apps, where you need to deal with separate defined controllers, services and directives in different files which are required to get loaded for performing some part of functions. So it would be best practice to load controllers or services JavaScript file dynamically when required instead of loading all bunch of file at single hit, which might result in increasing latency time of response of page. Well this could be easily achieved with the help of RequireJs, where we just need to set and call required files, while the rest RequireJs would worry to do the importing.

Load Dynamically JavaScript file in AngularJs with RequireJs
Load Dynamically JavaScript file in AngularJs with RequireJs

As at this moment, I am also new to AngularJs, so I need to searched for the solution, for how to load JavaScript file dynamically in AngularJs, all around the Google. And now I am up with the perfect and simplest solution. With the help of AngularAMD and requirejs, allows you to build AMD (asynchronous module definition) modules, within some minutes.

“angularAMD is an utility that facilitates the use of RequireJS in AngularJS applications supporting on-demand loading of 3rd party modules such as angular-ui.” – Marcos Lin

Example – Load Dynamically JavaScript file in AngularJs with RequireJs

Here is the sample and description to load modules Dynamically in AngularJs projects. Requirement:
angularAMD.js
require.js
angular-route.js

Lets take a simple converter application, which will facilitates conversion of temperature and length, where temperature controller and length controller modules is defined in separate files. Now our target is to load temperature or length controller file, when required.

Firstly create boot.js, which will be loaded initially, where we will define modules path, shim and dependency. Here is how boot.js looks like:

In boot.js:

require.config({
    baseUrl: "js",
    paths: {
        //defining the variables to the path of resepective js files present in the project foler.
        angular: "../lib/angular.min",      
        "angular-route": "../lib/angular-route.min",
        angularAMD: "../lib/angularAMD"
    },
    shim: {
        //as requirejs follows AMD, so shim confirms the loading of dependent file in sequence.
        //here angularAMD and angular-route is dependent on angular, so angular is loaded before the two
        angularAMD: ["angular"],
        "angular-route": ["angular"]
    },
    //deps will execute app.js
    deps: ["app"]
});

In app.js

define(["angularAMD", "angular-route"], function(angularAMD) {
    var app = angular.module("webapp", ["ngRoute"]);    
    app.config(function($routeProvider) {
        $routeProvider
        .when("/", angularAMD.route({
            templateUrl: "template/home.html",
            controller: "HomeCtrl",
            //if all controller javascript file is defined in boot.js file,
            //there is no need to define controllerUrl in any of the case.
            controllerUrl: "js/HomeCtrl.js"
        }))
        .when("/temperature", angularAMD.route({
            templateUrl: "template/View.html",
            controller: "TemperatureController",
            controllerUrl: "js/TemperatureCtrl.js"
        }))
        .when("/length", angularAMD.route({
            templateUrl: "template/View.html",
            controller: "LengthController",
            controllerUrl: "js/LengthCtrl.js"
        }))
        .otherwise({
            redirectTo: "/"
        })
    });

    //this will bootstrap the application. There is no need to define 'ng-app' in HTML file
    return angularAMD.bootstrap(app);
});

In index.html:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="css/style.css">
    <!-- data-main define the entry point for RequireJS configuration-->
    <script data-main="js/boot.js" src="lib/require.js"></script>
  </head>
  <body>
    <div ng-view></div>
  </body>
</html>

In View.html

<h1><a href="#/">Home</a></h1>

<div id="inputElem">{{fromUnit}} <input class="item item-input" type="number" placeholder="0" step="0.01" ng-model="data" ng-change="getValue(data)"></div>

<div id ="rowvalue" class="row" ng-repeat="(key,value) in result">
	<div id="colvalue" class="col-sm-6">{{key}} : {{value}}</div>
</div>

In HomeCtrl.js

define(["app"],function(app){
	app.controller("HomeCtrl",function($scope){
		console.log("home controller is loaded");
})
});

In TemperatureCtrl.js

define(["app"],function(app){
    app.controller('TemperatureController', function($scope) {	
    	$scope.fromUnit = "CELSIUS";
		$scope.result = {'CELSIUS': '0', 'KELVIN':'0', 'FAHRENHEIT' : '0'};
		
                  $scope.getValue = function(temp){
			Fahrenheit = (temp * 9 / 5) + 32;
			Kelvin = temp*1.0 + 273.15;
			Celsius = temp;
			$scope.result = {'CELSIUS':Celsius, 'KELVIN':Kelvin, 'FAHRENHEIT' : Fahrenheit};
		};
	})
});

In LengthCtrl.js

define(["app"],function(app){
    app.controller('LengthController', function($scope) {	
    	$scope.fromUnit = "CENTIMETER";
		$scope.result = {'CENTIMETER':'0', 'METER':'0','INCH':'0'};
		 
                 $scope.getValue = function(temp){
			var cm = temp;
			var m = 0.01 * temp;
			var inch = 0.393700787401575 * temp; 
			$scope.result = {'CENTIMETER':cm, 'METER':m,'INCH':inch};
		};
	})
});

Here is the working demo of the above given code:

Demo : Load Dynamically JavaScript file in AngularJs with RequireJs

If you want to test for dynamically loading of JavaScript, open up Network tab of your browser and see how files get loaded when the page is called. If you are getting any difficulty, do comment below, we would try to resolve it. Also do share if you have another solution for the same.