Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the services from RESTful API in my angularjs page?

I am very new to angularJS. I am searching for accessing services from RESTful API, but I didn't get any idea. How can I do that?

like image 433
anilCSE Avatar asked May 06 '13 07:05

anilCSE


People also ask

How do I access REST services?

Step #1 – Enter the URL of the API in the textbox of the tool. Step #2 – Select the HTTP method used for this API (GET, POST, PATCH, etc). Step #3 – Enter any headers if they are required in the Headers textbox. Step #4 – Pass the request body of the API in a key-value pair.

Which AngularJS services allows interacting with a RESTful backend?

AngularJS's $resource service is easier to use than $http for interacting with data sources exposed as RESTful resources. It is also easier now to understand what the code in our controllers is doing.


2 Answers

Option 1: $http service

AngularJS provides the $http service that does exactly what you want: Sending AJAX requests to web services and receiving data from them, using JSON (which is perfectly for talking to REST services).

To give an example (taken from the AngularJS documentation and slightly adapted):

$http({ method: 'GET', url: '/foo' }).   success(function (data, status, headers, config) {     // ...   }).   error(function (data, status, headers, config) {     // ...   }); 

Option 2: $resource service

Please note that there is also another service in AngularJS, the $resource service which provides access to REST services in a more high-level fashion (example again taken from AngularJS documentation):

var Users = $resource('/user/:userId', { userId: '@id' }); var user = Users.get({ userId: 123 }, function () {   user.abc = true;   user.$save(); }); 

Option 3: Restangular

Moreover, there are also third-party solutions, such as Restangular. See its documentation on how to use it. Basically, it's way more declarative and abstracts more of the details away from you.

like image 82
Golo Roden Avatar answered Oct 10 '22 00:10

Golo Roden


The $http service can be used for general purpose AJAX. If you have a proper RESTful API, you should take a look at ngResource.

You might also take a look at Restangular, which is a third party library to handle REST APIs easy.

like image 35
Aleksander Blomskøld Avatar answered Oct 10 '22 01:10

Aleksander Blomskøld