;

Calling Restful API in Angular JS

admin 06:47:pm Jan 29 2017

Here, we will call the RESTful API from angular js.

Suppose there is a RESTful API which URL is: http://localhost:8080/saveDetails

And I want to save employee information using angular js. We will call the above API using "POST" method.

There is a button in html page. When I will click this button it will save the employee information. Data is being sent in JSON format.

Here, I am using "$resource" service to call RESTful API. The $resource service is a factory which creates a resource object that lets you interact with RESTful server-side data sources as per the angular js documentation.


Note: It requires the ngResource module of angular js to be installed.

1. Testing.html

<!DOCTYPE html>
<html ng-app='demoApp'>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="../angular/angular.js"></script>
<script src="../angular-resource/angular-resource.js"></script>
<title></title>
</head>
<body ng-controller='demoCtrl'>
<input type="button" value="Submit" ng-click="saveDetails()" />
<script src="testing.js"></script>
</body>
</html>


2. testing.js

var demoApp = angular.module("demoApp", ['ngResource']);
demoApp.factory('employee', function ($resource) {
return $resource('/employee/:cmd', {}, {
saveDetails: { method: 'POST', isArray: true, params: { cmd: 'saveDetails' } },
});
});
demoApp.controller("demoCtrl", ['$scope', 'employee', function ($scope, employee) {
var config = {
"empID": 1001,
"firstName": "My Name",
};
$scope.saveDetails = function () {
employee.saveDetails(config, function (data) {
// here data will come as JSON array in "data" object
// it will be used to show input source fields
document.write(JSON.stringify(data));
}, function (err) {
console.log('saveDetails error:', err);
});
}
}
]);

Hope this is helpful example for you. Leave your comment and provide your suggestion if any.

Related Post

Comments

No comments yet. Be the first!

Add Comment

Adding comments has been disabled.