Tech
Forums
Jobs
Books
Events
Interviews
Live
More
Learn
Training
Career
Members
Videos
News
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Call Rest Service In AngularJS
WhatsApp
Gul Md Ershad
8y
16.3
k
0
1
25
Blog
Introduction
AngularJs provides
$http
for the communication withthe endpoint by calling
Restful
endpoint. It issues XHR and JSONP calls. It uses several methods like GET, POST, PUT, DELETE, HEAD, etc.
The
$http.GET
or
$http.POST
method accepts any JavaScript object or a string value as the data parameter. It converts the JavaScript data object into JSON String.
Rest Service Call using With $http
myApp.factory(
'myService'
, [
'$http'
,
'$q'
, function ($http, $q)
{
function getBookData()
{
var deferred = $q.defer();
$http.
get
(
'https://myRestServiceUrl'
).success(function (data)
{
deferred.resolve(data);
}).error(function (err)
{
console.log(
'Error retrieving data'
);
deferred.reject(err);
});
return
deferred.promise;
}
return
{
getBookData: getBookData
};
}]);
Use $http Service method into Controller
var myApp = angular.module(
'myApp'
, []);
myApp.controller(
'myCtrl'
, [
'$scope'
,
'myService'
, function ($scope, myService)
{
function fetchBookDetails()
{
$scope.isLoading =
true
;
myService.getBookData().then(function (data)
{
$scope.bookDetails = data.books;
});
}
fetchBookDetails();
$scope.getBookDataDetails = function ()
{
fetchBookDetails();
};
}]);
$q
$q is a service that helps to run functions asynchronously and it returns value whenan asynchronous task completes the process.
$q includes instances or featurs in the form of
$q.defer()
:
It exposes the associated promise instance as well as APIs that can be used for signaling the successful or unsuccessful completion.
The instance of $q.defer() includesthe below methods:
resolve:
It resolves the derived promise.
Example:
.success(function (data) {
deferred.resolve(data);
})
reject:
It rejects the derived promise with the reason $q.reject.
Example:
.error(function (err) {
console.log(
'Error retrieving data'
);
deferred.reject(err);
});
promise:
It returns promise after resolving the service response.
Example:
return
deferred.promise;
Call Rest Service In AngularJS
Up Next
Loading Image For Every HTTP Service Call In AngularJS
Ebook Download
View all
Hands-On With AngularJS Using ASP.NET
Read by 12.1k people
Download Now!
Learn
View all
Membership not found