1

Is there a more elegant/correct way to compose an url with $http in AngularJS?

I find my self doing a lot of this:

$http.post('/api/' + model_id + '/' + id).success(function(data){
  //do something ..
});

and wandering if there was something like this (a little more readable)

$http.post('/api/:model_id/:id', {param1, param2}).success(function(data){
  //do something ..
});

Thanks

3
  • 2
    First of all, success is deprecated in favor of the standard then. Commented Dec 4, 2015 at 13:25
  • Thanks. I'll keep that in mind Commented Dec 4, 2015 at 13:25
  • If your requirement is to consume lightweight REST api, you can use $resource. It is wrapper over $http that supports the url format that you are looking for. Commented Dec 4, 2015 at 13:30

3 Answers 3

1

I use the following pattern:

o in a service called resources I create resources as follows (assuming my webservces are unter the URL path /webapi):

angular.module('myApp')
  .factory('resources', function ($resource) {
    var baseUrl = location.pathname + 'webapi';
    return {
      baseUrl: baseUrl,
      myServiceResource: $resource(baseUrl + '/my/service/:pathParam'),
      myOtherServiceResource: $resource(baseUrl + '/my/other/service')
      // etc.
    };
  });

o in a controller or another service you can then simply reference the resources service and use the globally defined resources (which are created only once):

angular.module('myApp')
  .factory('aService', function (resources) {
    // pathParam matches the parameter :pathParam in the URL
    // param1 and param2 are passed as query parameters
    var parameters = { pathParam: "pathValue", param1: "aValue", param2: "anotherValue" };
    var response = resources.myServiceResource.get(parameters, function() {
        // do something on success
        doSomething(response.result);
      }, function(httpResponse) {
        // do something on error
      });
  });
Sign up to request clarification or add additional context in comments.

Comments

0

Not with $http directly, but it seems you are looking for $resource (https://docs.angularjs.org/api/ngResource/service/$resource).

Example from docs:

// Define CreditCard class
var CreditCard = $resource('/user/:userId/card/:cardId',
 {userId:123, cardId:'@id'}, {
  charge: {method:'POST', params:{charge:true}}
 });

// We can retrieve a collection from the server
var cards = CreditCard.query(function() {
  // GET: /user/123/card
  // server returns: [ {id:456, number:'1234', name:'Smith'} ];

  var card = cards[0];
  // each item is an instance of CreditCard
  expect(card instanceof CreditCard).toEqual(true);
  card.name = "J. Smith";
  // non GET methods are mapped onto the instances
  card.$save();
  // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
  // server returns: {id:456, number:'1234', name: 'J. Smith'};

  // our custom method is mapped as well.
  card.$charge({amount:9.99});
  // POST: /user/123/card/456?amount=9.99&charge=true {id:456,         number:'1234', name:'J. Smith'}
});

// we can create an instance as well
var newCard = new CreditCard({number:'0123'});
newCard.name = "Mike Smith";
newCard.$save();
// POST: /user/123/card {number:'0123', name:'Mike Smith'}
// server returns: {id:789, number:'0123', name: 'Mike Smith'};
expect(newCard.id).toEqual(789);

1 Comment

Thanks. I'm not using resource right now, but i will keep it in mind when i do.
0

I use the following pattern because it allows me to implement my own error handling logic when API calls is failed, also I found that it is readable and easy to understand.

angular.module('myApp')
  .service('myService', function($http, $q) {
    var baseUrl = location.pathname + 'webapi';
      return({
        setService: setService,
        getService: getService
      });

    function setService(param1, param2) {
      var request = $http({
        method: 'post',
        url: baseUrl,
        params: {
          param1: param1,
          param2: param2
        }
      });
      return ( request.then ( handleSuccess, handleError) );
    }

    function getService(param1, param2) {
      var request = $http({
        method: 'get',
        url: baseUrl,
        params: {
          param1: param1,
          param2: param2
        }
      });
      return ( request.then ( handleSuccess, handleError) );
    }  

    function handleError( response ) {
      // Implement our own failure message if there is none
      if ( !angular.isObject(response.data) || !response.data.message) {
        return($q.reject("Failed to get data.") );
      }
      return($q.reject(response.data.message));
    }

    function handleSuccess( response ) {
      return response;
    }
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.