0

I'm new to AngularJS and I needed to know if we can make a jQuery like Ajax call in Angular and wanted to know it's complete syntax, if anyone could help me making the whole code syntax.

Example in jQuery I could do something like -

$.ajax(
{
      url: 'someURL',
      type: 'POST',
      async: false,
      data:
      {
          something: something,
          somethingelse: somethingelse
      },
      beforeSend: function()
      {
          $('#someID').addClass('spinner');
      },
      success: function(response)
      {
          $('#someID').removeClass('spinner');

          console.log(response);              
      },
      complete: function(response)
      {
           $('#someID').removeClass('spinner');

           console.log(response);
      },
      error: function (errorResp)
      {    
           console.log(errorResp);
      }
});

Now here's what I found out on making http call in Angular, Need help in building the complete syntax, with all possible options -

var req = {

       method: 'POST',
       url: 'someURL',
       headers: {
            'Content-Type': undefined
       },
       data: {
             //goes in the Payload, if I'm not wrong 
             something: 'something' 
       },
       params:{
              //goes as Query Params
              something: 'something',
              somethingElse: 'somethingElse'
       }
}

$http(req)
.then(function()
{
   //success function    
}, 
function()
{
   //Error function    
});

now what if I want to attach a spinner on some id in the BeforeSend function like in jQuery and remove the spinner in success, What is the Angular's way as a like to like for BeforeSend or making the http call async?

4
  • why do you need a beforeSend at all? Just set up the spinner before the $http call (or even after which will also work because the call is asynchronous) and remove it in .then function? Commented Jun 3, 2016 at 7:33
  • Yes, I could make temporary fixes no doubt, i just wanted to know if there is any standard way in Angular like jQuery has. Commented Jun 3, 2016 at 7:35
  • it is not a temporary fix, it is a very normal way of doing what you want. I personally find the jQuery way to be an overkill. There is absolutely no need for any beforeSend function. Commented Jun 3, 2016 at 7:47
  • @Aniruddharaje that's not for just showing spinner in that. bedoreSend has other actual usage. Commented Jun 3, 2016 at 8:33

5 Answers 5

1

Angular even let you control this better :). Two ways can be chosen here:

1. Wrapping $http

You can write for each request with by using a wrapper of $http which will add some methods before and after you made request

app.factory('httpService',function($http){
    function beginRequest() {};
    function afterRequest() {};
    return {
        makeRequest: function(requestConfig){
             beginRequest();
             return $http(requestConfig).then(function(result){
                 afterRequest(result);
             });
        }
    }      
}) 

Then each time you can call this function to make a request. This is not new.

2. Using interceptor

Angular has a better way to handle for all request. It use a new concept named 'interceptor'. You write your interceptor as a normal service and push one or many interceptors into $http service and depend on type of interceptor, it will be called each time your request happen. Look at this picture to think about interceptor: enter image description here

Some common task for interceptor can be: Add/remove a loading icon, add some more decorator to your http config such as token key, validate request, validate responded data, recover some request...

Here is example of a interceptor that add a token key into headers of a request

app.service('APIInterceptor', function($rootScope, UserService) {
    var service = this;

    service.request = function(config) { 
        var currentUser = UserService.getCurrentUser(),
            access_token = currentUser ? currentUser.access_token : null;

        if (access_token) {
            config.headers.authorization = access_token;
        }
        return config;
    };

    service.responseError = function(response) {
        return response;
    };
})

Then add interceptor to your $http:

app.config(['$httpProvider', function($httpProvider) {  
    $httpProvider.interceptors.push('APIInterceptor');
}]);

Now all request will be added a token key to header. cool right?

See here for more information:

Sign up to request clarification or add additional context in comments.

Comments

0

there is eveyrthing here to help with your question :https://docs.angularjs.org/api/ng/service/$q http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/

Comments

0

$http functions are async by default.

And regarding the beforesend function, you could wrap the http call in a function and add the spinner just before making the call and remove it in the success call back. Something like this,

var makeHttpRequest = function(){
   $('#someID').addClass('spinner');
   $http(req).then(function(){
     $('#someID').removeClass('spinner');
     //rest processing for success callback
   },function(){
     $('#someID').removeClass('spinner');
     //Error callback
   });
}

2 Comments

so how would I make the http call synchronous if I need to?
$http calls are asynchronous by default. You could make it synchronous by the implementation of $q. and making the wrapper function return a promise once the $http call is completed. You could read about $q from here link
0

The way I have implemented complex get and post in my angular application is as below:

Create a CRUDService as below:

yourApp.service('CRUDService', function ($q, $http) {
    this.post = function (value, uri) {
        var request = $http({
            method: "post",
            url: uri,
            data: value
        });
        return request;
    }

    this.get = function (uri) {
        var request = $http({
            method: "get",
            url: uri
        });
        return request;
    }
});

As you can see this service simply returns a get/post object. Somewhere in my controller I use this service as below:

$('#exampleButton').button("loading");  //set the element in loading/spinning state here
var getObj = CRUDService.get("/api/get/something");
getObj.then(function(data){
    //do something
    $('#exampleButton').button("reset"); //reset element here
}, function(err){
    //handle error
    $('#exampleButton').button("loading"); //reset element here
});

$('#exampleButton').button("loading");  //set the element in loading/spinning state here
var postObj = CRUDService.post(postData,"/api/get/something");
postObj.then(function(data){
    //do something
    $('#exampleButton').button("reset"); //reset element here
}, function(err){
    //handle error
    $('#exampleButton').button("loading"); //reset element here
});

I hope this helps :)

Comments

0

The http call is async - it returns a promise that you can then handle with the try() and catch() methods. You can simply wrap your calls i.e.

function makeRequest() {
  $scope.showSpinner = true;
  $http
    .get('http://www.example.com')
    .then(function (response) {
      $scope.showSpinner = false;
    })
    .catch(function (err) {
      $scope.showSpinner = false;
    });
}

If you would however like you use familiar syntax akin to jQuery then you can push your own custom interceptors. This will allow you intercept the requests and response and do whatever you want. In the below example we call functions if they are defined.

angular
  .module('app', [])
  .config(appConfig)
  .factory('HttpInterceptors', httpInterceptors)
  .controller('MyController', myController);

// app config
appConfig.$inject = ['$httpProvider'];

function appConfig($httpProvider) {
  // add out interceptors to the http provider
  $httpProvider.interceptors.push('HttpInterceptors');
}

// http interceptor definition
function httpInterceptors() {
  return {
    request: function(request) {
      if (angular.isFunction(request.beforeSend)) {
        request.beforeSend(); 
      }
      return request;
    },
    response: function(response) {
      if (angular.isFunction(response.config.onComplete)) {
        response.config.onComplete(); 
      }
      return response; 
    }
  }
}

// controlller
myController.$inject = ['$scope', '$http', '$timeout'];

function myController($scope, $http, $timeout) {

  $scope.showSpinner = false;
  
  $http({
    method: 'GET',
    url: 'https://raw.githubusercontent.com/dart-lang/test/master/LICENSE',
    beforeSend: function() {
      $scope.showSpinner = true;
    },
    onComplete: function() {
      $timeout(function() {
        console.log('done');
        $scope.showSpinner = false;
      }, 1000);
    }})
    .then(function(response) {
      console.log('success');
    })
    .catch(function(err) {
      console.error('fail');
    });
}
.spinner {
 background-color: red; 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>

<div ng-app='app' ng-controller='MyController'>
  <div ng-class='{spinner: showSpinner}'>
    Hello World!
  </div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.