Tuesday, July 28, 2015

Inject Angular Service to Controller

In AngularJS Dependency Injection is achieved by injecting objects to the controller, in normal implementations we use the $scope object in the controller to set values and pass it to the view for display.

In the following example we shall create a service and inject the service to the controller, this way all the data used in the controller are fed from the service, the service can be changes or pass different service objects to test the controller and the view.

Dependency Injection in Angular?

In AngularJS dependency injection is achieved by injecting objects to the controller, in normal implementations we use the $scope object in the controller to set values and pass it to the view for display. The following is an example of normal controller implementation without using Dependency injection.

What is Dependency Injection?

Dependency Injection is a software design pattern which is used to improve testability of applications. Dependency Injection loosely couples the various components of the application thereby improve testability of the various components independently.

If the objects to be used in a class are initialized locally in the class, then it creates a dependency and makes the objects tightly bound to the class. The below class is an example without using Dependency Injection, notice that the objEmpRepository object is initialized within the class, hence it is tightly bound to the class.

Saturday, July 25, 2015

AngularJS Ajax Overview

AngularJS $http.delete Ajax calls

In the post AngularJS Ajax using $http we saw that we can perform Ajax calls to the server in AngularJS using $http service, and we saw that $http supports Get, Post, Put and Delete operations. In this post we shall see on how to make a $http.delete Ajax call in AngularJS

The following example shows how to make a $http.delete call to an Asp.Net Web API Controller method.
WebAPI Post Method
    public class PackageController : ApiController
    {
        PkgEntities objDBContext = new PkgEntities();
        //
        [HttpDelete]
        public string Delete(int id)
        {
            try
            {
                Package currPackage = (from Packages in objDBContext.Packages
                                       where Packages.PackageId == id
                                       select Packages).First();
                //
                objDBContext.Packages.Remove(currPackage);
                objDBContext.SaveChanges();
                return "Package " + currPackage.Name + " deleted Succesfully";
            }
            catch (Exception ex)
            {
                return "Error: " + ex.Message.ToString();
            }
   }
}

AngularJS call to WebAPI Get method
        $http.delete(GetRootPath() + "Package/" + packageId)
           .then(function (results) {
               //Success;
               try {
                   //alert(results.data);
               }
               catch (err) {
                   alert(err.message);
               }
           }, function (results) {
               //error
               alert("Error: " + results.data + "; "
                                     + results.status);
           })


The $http.delete method calls the server side WebAPI Post() method with the id of the package to be deleted as the parameter. The WebAPI contoroller’s Delete method automatically receives this call and deletes the corresponding package from the Database Context and returns a success/failure message to AngularJS. The AngularJS client method receives the message and displays it to the end user.

AngularJS $http.post Ajax calls

In the post AngularJS Ajax using $http we saw that we can perform Ajax calls to the server in AngularJS using $http service, and we saw that $http supports Get, Post, Put and Delete operations. In this post we shall see on how to make a $http.post Ajax call in AngularJS

The following example shows how to make a $http.post call to an Asp.Net Web API Controller method.
WebAPI Post Method
    public class PackageController : ApiController
    {
        PkgEntities objDBContext = new PkgEntities();
        //
        [HttpPost]
        public string Post(Package objPackage)
        {
            try
            {
                objDBContext.Packages.Add(objPackage);
                objDBContext.SaveChanges();
                return "Package " + objPackage.Name + " added Succesfully";
            }
            catch (Exception ex)
            {
                return "Error: " + ex.Message.ToString();
            }
 }
}
AngularJS call to WebAPI Get method
    this.AddPackage = function (scope) {
        var dataObj = {
            Name: scope.Name,
            Description: scope.Description,
            PackageSQL: scope.PackageSQL,
            Status: scope.Status
        };
        //
        $http.post(GetRootPath() + "Package", dataObj)
           .then(function (results) {
               //Success;
               try {
                   alert(results.data);
               }
               catch (err) {
                   alert(err.message);
               }
           }, function (results) {
               //error
               alert("Error: " + results.data + "; "
                                     + results.status);
           })

    }

The $http.post method creates a JSON object objData calls the server side WebAPI Post() method and passes the object as parameter to the WebAPI method. The WebAPI contoroller method receives the package object from the $http.post call and inserts a new package to the database context and returns a success/failure message to AngularJS. The AngularJS client method receives the message and displays it to the end user.

AngularJS $http.get Ajax calls

In the post AngularJS Ajax using $http we saw that we can perform Ajax calls to the server in AngularJS using $http service, and we saw that $http supports Get, Post, Put and Delete operations. In this post we shall see on how to make a $http.get Ajax call in AngularJS

The following example shows how to make a $http.get call to an Asp.Net Web API Controller method.
WebAPI Get Method
    public class PackageController : ApiController
    {
        PkgEntities objDBContext = new PkgEntities();
        //
[HttpGet]
public dynamic Get()
{
var lstPackages = (from Packages in objDBContext.Packages
orderby Packages.PackageId
select new { Packages.PackageId, Packages.Name, Packages.Description, Packages.PackageSQL, Packages.Status });
//
return lstPackages;
}
}

AngularJS call to WebAPI Get method
        $http.get(“http://localhost:7630/api/Package")
            .then(function (results) {
                //Success;
                try {
                    scope.packageList = results.data;
                }
                catch (err) {
                    alert(err.message);
                }
            }, function (results) {
                //error
                alert("Error: " + results.data + "; "
                                      + results.status);
            })

The $http.get method calls the server side WebAPI Get() method, collects the response and stores it in the  packageList property of the $scope object.

$http vs JSONP for cross-site request

In the previous posts we saw on how to make Ajax requests using $http and JSONP, we also saw that $http does not support cross-site server requests, and JSONP supports it. In this post we shall see an example of making cross-site service requests using $http and JSONP and observer the responses in both the cases.

The following example makes the same Ajax calls using JSONP and $http, let us observe the response from both the requests.

Monday, July 20, 2015

How JSONP enables cross-site request

In the previous post AngularJS Ajax using$http JSONP we saw on using JSONP to make cross-site requests, i.e the AnjularJS client and the service/API are located in different domains, by default browsers do not allow cross-site Ajax requests.

JSONP stands for JSON with padding, JSONP enables cross-site requests using the <script> tag, normal $http requests are sends server request URL as plain text, hence browsers reject the requests made to different domains, JSONP pads the requests within <script> tags and sends it to the server, browsers do not enforce same-origin validation for content in the <script> tag hence JSONP requests by-pass the validations and thereby enable us to make cross-site requests from the client to the server.

AngularJS Ajax using $http JSONP

In the previous post AngularJS Ajax using $http, we saw on how to make Ajax calls in AngularJS using $http, we also saw that we cannot make cross site calls using the $http service, but in practical situations we might have to call services/APIs deployed in a different server/domain, example could be making service / API calls to 3rd part services which are deployed in the Vendor’s server.

To overcome this, the $http service supports making Ajax calls using JSONP, the normal Ajax calls made using $http use the XMLHttpRequest object which does not support cross site referencing, however we can modify the request a bit to make JSONP calls to support cross domain.

The syntax for making JSONP Ajax calls using $http is as follows
$http({
       method: 'JSONP',
       url: 'serviceURL'?callback=JSON_CALLBACK'
}).success(function(data, status, headers, config)
{
           // Process response for Success here
}).error(function(data, status, headers, config)
{
          // Process response for Failure here
});

AngularJS Ajax using $http

In the previous post Ajax using AngularJS, we saw on what Ajax is and its need in modern web development tools, in this post we shall see on Ajax is supported in AngularJS using the $http service.


$http is an important service in AngularJS which helps in making Ajax calls to the server, $http takes the service URL to be invoked as a parameter, makes calls to the server gets the response and service and passes it back to Angular

The syntax for making Ajax calls using $http is as follows
$http.get('serviceURL').
  success(function(data, status, headers, config) {
          // Process response for Success here
  }).
  error(function(data, status, headers, config) {
          // Process response for Failure here
  });

The $http Ajax calls supports methods success() and error() to handle the response from the server end, the method names are self-descriptive they are used to handle success and error scenarios from the Ajax calls.

$http supports Get, Post, Put and Delete operations, all these take the service URL as parameters, the Post and Put variant in addition takes the Post data which is to be submitted to the service.

The $http service communicates with the server using XMLHttpRequest, due to this Ajax calls made using $http should be within the same domain, i.e both the client application and the service should be hosted in the same domain, calls made to a service/API in a different domain will fail.

Ajax using AngularJS

Ajax stands for Asynchronous JavaScript and XML, as the name suggests Ajax is used for asynchronous operations between the client and the server. Here by client we refer to the AngularJS layer and by server we refer to the API Server/Service.

Thursday, July 16, 2015

AngularJS MVVM Pattern Overview

Implement ViewModel Pattern using AngularJS

In the previous posts we saw in detail about MVVM pattern and its support in AngularJS


In this post we shall see a practical implementation of MVVM pattern in AngularJS, we will have an Asp.Net Web API service activing as the model (Server Side) and 2 different views in AngularJS consuming the same model, each view will have its own ViewModel ($scope and controller) and display the data from the same model (Asp.Net Web API) in different formats.
JSON response from API Server, this is the common service call for both the views, the model object is the same for both the views.

[
    {
        "PackageId": 1,
        "Name": "Merge",
        "Description": "Merge Package",
        "Status": "New"
    },
    {
        "PackageId": 2,
        "Name": "Delete",
        "Description": "Delete Package",
        "Status": "New"
    },
    {
        "PackageId": 3,
        "Name": "Update",
        "Description": "Update Package",
        "Status": "New"
    }
]

View displaying contents in a List

<!-- http://localhost:42395/UILayer/PackageListView.html -->
<html ng-app="PackageListViewApp">
<head>
    <meta charset="utf-8" />
    <title>AngularJS ViewModel - PackageListView</title>
</head>
<body ng-controller="PackageListViewController">
<table>
    <tr>
        <td colspan="4">{{title}}</td>
    </tr>
    <tr>
        <td colspan="4"><hr /></td>
    </tr>
    <tr>
        <td colspan="4">
            <ul ng-repeat="Package in ListViewModel">
                <li>{{ Package.PackageId }} - {{ Package.Name }}</li>
            </ul>
        </td>
    </tr>
</table>
<script src="ScriptLibrary/angular.min.js"></script>
<script src="Controllers/PackageListViewController.js"></script>
</body>
</html>

List View Controller (PackageListViewController.js)

var packageListViewApp = angular.module("PackageListViewApp", [])
packageListViewApp.controller("PackageListViewController", function ($scope, $http) {
    $scope.title = "Packages - List View";
    $scope.packageList = {};
    $scope.ListViewModel = {};
    var pkgList = [];
    var i = 0;
    //$scope.GetPackageList = function (scope) {
        $http.get("http://localhost:7630/api/Package")
            .then(function (results) {
                //Success;
                try {
                    // JSON received from the Server
                    $scope.packageList = results.data;
                    //
                    // Iterate through the JSON and create ViewModel object array
                    angular.forEach($scope.packageList, function (item) {
                        pkgList[i] = new Package(item.PackageId, item.Name);
                        i++;
                    });
                    //
                    // Return ViewModel object Array to the View
                    $scope.ListViewModel = pkgList;
                }
                catch (err) {
                    alert("Error: " + err.message);
                }
            }, function (results) {
                //error
                alert("Error: " + results.data + "; "
                                      + results.status);
            })
    //}
});

var Package = function (PackageId, Name) {
    this.PackageId = PackageId;
    this.Name = Name;
};

View displaying contents in a Grid

<!-- http://localhost:42395/UILayer/PackageListView.html -->
<html ng-app="PackageGridViewApp">
<head>
    <meta charset="utf-8" />
    <title>AngularJS ViewModel - PackageGridView</title>
</head>
<body ng-controller="PackageGridViewController">
<table>
    <tr>
        <td colspan="4">{{title}}</td>
    </tr>
    <tr>
        <td colspan="4"><hr /></td>
    </tr>
    <tr>
        <td colspan="4">
            <table border="1" style="padding:0 0 0 0;" cellspacing="0">
                <tr>
                    <td>PackageID</td>
                    <td>Package Name</td>
                    <td>Description</td>
                    <td>Status</td>
                </tr>
                <tr ng-repeat="Package in GridViewModel">
                    <td>{{ Package.PackageId }}</td>
                    <td>{{ Package.Name }}</td>
                    <td>{{ Package.Description }}</td>
                    <td>{{ Package.Status }}</td>
                  </tr>
                </table>
        </td>
    </tr>
</table>
<script src="ScriptLibrary/angular.min.js"></script>
<script src="Controllers/PackageGridViewController.js"></script>
</body>
</html>

Grid View Controller (PackageGridViewController.js)

var packageListViewApp = angular.module("PackageGridViewApp", [])
packageListViewApp.controller("PackageGridViewController", function ($scope, $http) {
    $scope.title = "Packages - Grid View";
    $scope.packageList = {};
    $scope.GridViewModel = {};
    var pkgList = [];
    var i = 0;
    //$scope.GetPackageList = function (scope) {
        $http.get("http://localhost:7630/api/Package")
            .then(function (results) {
                //Success;
                try {
                    // JSON received from the Server
                    $scope.packageList = results.data;
                    //
                    // Iterate through the JSON and create ViewModel object array
                    angular.forEach($scope.packageList, function (item) {
                        pkgList[i] = new Package(item.PackageId, item.Name, item.Description, item.Status);
                        i++;
                    });
                    //
                    // Return ViewModel object Array to the View
                    $scope.GridViewModel = pkgList;
                }
                catch (err) {
                    alert("Error: " + err.message);
                }
            }, function (results) {
                //error
                alert("Error: " + results.data + "; "
                                      + results.status);
            })
    //}
});

var Package = function (PackageId, Name, Description, Status) {
    this.PackageId = PackageId;
    this.Name = Name;
    this.Description = Description; this.Description = Description;
    this.Status = Status;
};

Output : List View