Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add add request parameter to every Angular.js $http request (to start a xdebug session for example)

My hybrid application is based on AngularJS and uses a php REST api.

I would like to debug the php api directly from my Angular app instead to use REST console or Postman. It would save a lot of time especially for POST and PUT requests.

In order to do so I would need to add a parameter to each request like so:

http://localhost:8000/api/contacts?XDEBUG_SESSION_START=PHPSTORM

Can I config $http to do so?

like image 359
curuba Avatar asked Aug 01 '15 11:08

curuba


1 Answers

You can use httpInterceptor for that (official $http documentation contains more info)

// register the interceptor as a service
$provide.factory('xdebugInterceptor', function($q) {
  return {
    // optional method
    'request': function(config) {
      // do something on success

      // !!! adjust the config object
      // add request param XDEBUG_SESSION_START=PHPSTORM
      // it will be added to every made request

      config.params = config.params || {};
      config.params.XDEBUG_SESSION_START: "PHPSTORM";

      return config;
    },

    // optional method
   'requestError': function(rejection) {
      // do something on error
      return $q.reject(rejection);
    },


    // optional method
    'response': function(response) {
      // do something on success
      return response;
    },

    // optional method
   'responseError': function(rejection) {
      // do something on error
      return $q.reject(rejection);
    }
  };
});

// make this conditional so you use it only in DEV mode
$httpProvider.interceptors.push('xdebugInterceptor');
like image 132
tomastrajan Avatar answered Sep 19 '22 19:09

tomastrajan