AngularJS
uses $http core service to read and send data to remote servers via the
browser's XMLHttpRequest object or via JSONP.
In ingularJS
you can send requests in different ways some I explained below
1. AJAX
calls via the $http service.
2. JSONP
calls via the $http service.
3. REST type
calls.
The $http
service is a function which takes a single argument -a configuration object,
that is used to generate an HTTP request and returns a promise.
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
The response object has following
properties
data {string|Object} : The response body transformed with
the transform functions.
status {number}:
HTTP status code of the response.
headers {function([headerName])} :Header getter function.
config {Object} : The configuration object that was
used to generate the request.
statusText {string} : HTTP status text of the response.
With $http
service you can use follwing shortcut methods,
$http.get
$http.head
$http.post
$http.put
$http.delete
$http.jsonp
$http.patch
1. AJAX calls via the $http service
AngularJS
uses $http service to read and send data to servers, server makes call to
database and retrieves required records. Practically AngularJS reads data in
Json format once data is ready $http server reads data from server, for more
understanding check following code.
Code Sample:
function EmployeeController($scope,$http) {
var url = "EmployeeData.txt";
$http.get(url).success( function(response)
{
$scope.Employees = response;
});
}
2. JSONP calls via the $http service
$http
service provides get, post and other functions mapped to http methods, like
“get” and “post” it also provides the function that we’ll need “jsonp”.
JSONP is
short for "JSON with Padding" and data returned using jsonp is
formatted differently, here the ‘p’ in Jsonp stands for padding which means
simply “Named Function”.
Syntax:
jsonp(url,
[config]);
Parameter
|
Description
|
URL(String)
|
Relative or absolute URL specifying
the destination of the request. The name of the callback should be the string
JSON_CALLBACK.
|
Config(Object)
|
This is optional configuration object.
|
How it works
1. A JSONP request is not sent like simple AJAX
calls using XHR objects. Instead, a <script> element is created and
inserted into the HTML page.
The src attribute contains the URL of the
remote service to call with the JSONP call. This URL should include any
parameters you need to send to the remote service.
2. When the
<script> element is inserted into the HTML page, the browser will load
the script from the given URL. That enables the remote service to send JavaScript
back to your application for execution.
The
JavaScript returned by the remote service should be a function call to an
existing JavaScript function in your HTML page.
Note
First ensure
your server supports Jsonp requests
reason Jsonp requests require explicit support on the server side.
Code Sample
var url = http://codechef4u.com/testdata.json?callback=JSON_CALLBACK";
var responseData = $http.jsonp( url,
{ params : {
p1 : "test 1"
,p2 : "test 2"
}
}
);
responseData.success(function(testData)
{
// your code with returned object
// ( in the "data" parameter ).
});
3. AngularJS Rest type Calls
You can use rest service in angular
js follwing are some options I explained ,
Option 1: Using $http service
AngularJS
$http service sends AJAX requests to web services and receiving data from them,
using JSON (Exactly what required for REST services).
Example:
$http({ method: 'GET', url: '/codechef4u.com/xyzservice' }).
success(function (data, status, headers, config) {
// your code on data
}).
error(function
(data, status, headers, config) {
// if any error log or report code
});
Option 2: $resource service
You can try
AngularJS another service named $resource service, the $resource service which
provides access to REST services in a more high-level fashion. You can use following
link for more details,
https://docs.angularjs.org/api/ngResource/service/$resource
Example:
var UsersData = $resource('/user/:userId',{ userId: '@id' });
var user = UsersData.get({ userId: 123 }, function () {
user.nkendre = true;
user.$save();
});
Option 3: Third party tools
You can try
also third-party solutions, such as Restangular.
See its documentation on how to use it. Go through documentation using following
GitHub link.
https://github.com/mgonto/restangular
AngularJS Ajax Code Example
View
<div ng-app="myAjaxApp" ng-controller="myAjaxCtrl">
<ul ng-repeat="post in posts">
<li>{{post.Title}}</li>
</ul>
</div>
script
var app =
angular.module("myAjaxApp", []);
app.controller("myAjaxCtrl", function ($scope, $http) {
$http.get('posts.json').
success(function
(data, status, headers, config) {
$scope.posts = data;
}).
error(function
(data, status, headers, config) {
// log error
alert('some error')
});
});
Jason File
[{ "Title":"learn
angular", "Description":"test data
for angular" },
{ "Title":"build an angular app", "Description":"another
dasdf sdf "}
]
धन्यवाद मित्रानो ...