Ajax requests with angularjs

  • error ( function ( err , status , headers , config ) { //process error scenario.
  • error ( function ( err ) { //handle error } ) } ] )
  • In many applications client is required to make requests to remote http servers to fetch data, or as we say make ajax requests, AngularJs provides $http service for making ajax requests to remote servers.
  • Success ( function ( response , status , headers , config ) { // config is an optional object to pass delete prams //process success scenario.
  • then ( function ( response ) { //wrap it inside another promise using then return response.

In this tutorial we just want to demonstrate a simple get and post request in angular js using the $http service. We will also learn to do the same in the preferred way, which is wrapping the $http in another service or factory.

@cipherTrick: Ajax requests with Angularjs

In many applications client is required to make requests to remote http servers to fetch data, or as we say make ajax requests, AngularJs provides $http service for making ajax requests to remote servers.

In this tutorial we just want to demonstrate a simple get and post request in angular js using the $http service.

We will also learn to do the same in the preferred way, which is wrapping the $http in another service or factory.

response variable contains the data returned by the API.

The syntax for put is same as post except you have to use the respective method.

$http service returns a promise object with success and error functions.

It supports actions such as get, post, put, delete and jsonp.

Get request example.

Wrapping $http request in another service/factory (Preferred way).

The recommended way to make an ajax call with angular js is to wrap $http request into a factory and then use it to serve data. This makes your code more organised and separates the concerns. Also it allows you to pre-process the received data and use it in multiple controllers.

Here if you notice I’m using the then method instead on success and error,this is because success returns the original $http promise where as by using then we can return a new promise, this helps us to process the data inside the factory and return only the required information.

Its perfectly fine to use success instead of then if you want the factory to return the original $http promise

Below is the html file for the above demo.

Angular js also allows you to set custom headers using the $http.defaults object.

This was a basic introduction to the Angular’s $http service, it can do a lot more then what we have seen over here.

Head over to the documentation to dive deeper.

Ajax requests with angularjs

You might also like More from author

Comments are closed, but trackbacks and pingbacks are open.