Monday, August 18, 2014

Working with AngularJS with Get/Post calls

Here is some code which will show how can we use get/post calls when working with AngularJS. For these code i assume that you are aware of some basic knowledge of AngularJS code and syntaxes. Also, for this examples i used WCF service as data source which returns expected results as i want for my use so you can change code or source of service as per your need.

(1) Get With Single Value : This function returns single string value.
HTML :  





AngularJS : 

var sample = function ($scope, $http) {
        $http({
            url: '/MyService.svc/DoWorkWithString'
        }).success(function (data) {
            $scope.stringResult = data.DoWorkWithStringResult;
        });
    };

(2) Get With List of values : This function returns list of Name & Count which are processed at UI and displayed to view.
HTML : 







AngularJS : 
var ListController = function($scope, $http) {
        var resultPromise = $http.get("MyService.svc/ListItems");
        resultPromise.success(function(data) {
            $scope.ListItems = data.ListItemsResult;
        });
    };

For the post operation, both function simply returns string value which could be any success/error message that we can pass to UI after completion of any
operation on posting.
(3) Post with single parameter : posts one valueHTML : 




Angular JS :
function FrmController($scope, $http) {
$scope.errors = [];
$scope.msgs = [];
$scope.Click = function () {
$scope.errors.splice(0, $scope.errors.length); // remove all error messages
$scope.msgs.splice(0, $scope.msgs.length);
$http({ method: 'POST', url: 'MyService.svc/ListTest', data: JSON.stringify($scope.idTest) }).success(function (data) {
                if (data != '') {
                    $scope.msgs.push(data);
                } else {
                    $scope.errors.push(data);
                }
            });
};

(4) Post with two parameter
HTML : 

Angular JS :
function FrmController($scope, $http) {
$scope.errors = [];
$scope.msgs = [];
$scope.Click = function () {
$scope.errors.splice(0, $scope.errors.length); // remove all error messages
$scope.msgs.splice(0, $scope.msgs.length);
$http({ method: 'POST', url: 'MyService.svc/ListTestTwo', data: JSON.stringify({"param1":"value1","param2":"value2"}) }).success (function (data) {
                if (data != '') {
                    $scope.msgs.push(data);
                } else {
                    $scope.errors.push(data);
                }
            });
};

So, That's it for AngularJS with Get/Post calls.

No comments:

Post a Comment