Search code examples
angularjsrestangularjs-controllerangularjs-factoryangularjs-http

Rest Webservice call in AngularJS ( promise )


AngularJS : 1.4.X
Scenario 1: Works fine
Scenario 2: Throws 404 error on line xhr.send(isUndefined(post) ? null : post); in angular.js

I'm trying to add inbuilt angular cache to our existing app, As i mentioned in scenario 1 we consume rest call in factory 'restFactory' and inject the factory to controller 'bookController', the promise is resolved and data loads fine.

Factory: restFactory

(function () {
    "use strict";
    angular.module('myApp').factory("restFactory",['$http','confi', function($http,config){

    function getBooks (){  
       return $http.get(config.serverName+"bookshelf/rest/books/data/geRestBooks");
    }
    return {
        getBooks : getBooks
    };
}]);
})();

Controller: bookController

   $scope.getComicbooks = function() {
        restFactory.getBooks().then(function(response) {        
            $scope.names = response.data;
        }, function(error) {
            $scope.error = error;
            $scope.names = [];
        });
    };

Now in scenario 2, I changed the service call in factory to object with more details. But i get exception from controller while resolving the promise ( i have only added the changed code )

function getBooks (){  
   return $http.get({
   cache: true,
   method: 'GET',
   url : config.serverName+"bookshelf/rest/books/data/geRestBooks"
   });
}

ERROR: angular.js:10765 GET http://127.0.0.1:53814/views/[object%20Object] 404 (Not Found)

Network Tab:
enter image description here In scenario#1 this would have been a method call getBooks


Solution

  • If you are going to specify the method, then you should just use the $http constructor method, not the get method.

    Instead of

    function getBooks (){  
       return $http.get({
          cache: true,
          method: 'GET',
          url : config.serverName+"bookshelf/rest/books/data/geRestBooks"
       });
    }
    

    Try

    function getBooks (){  
       return $http({
          cache: true,
          method: 'GET',
          url : config.serverName+"bookshelf/rest/books/data/geRestBooks"
       });
    }