Search code examples
angularjsangularjs-servicehttp-getangular-controller

Service and Controller to call api with a value in the end of api


I have a service call that I want to pass a value into the function to call the http.get api by id:

/home/api/order/1

My service looks like this:

angular.module("app")
.factory('Service', ['$http', function ($http) {
var urlBase = '/home/api/order/';
Service.getOrderbyorderid = function (orderid) {
        return $http.get(urlBase + orderid)
    };
});

What I have tried for my Controller is:

getOrderbyorderid ();
        function getOrderbyorderid () {
            $scope.orderid = $routeParams.orderid ;
            console.log($scope.orderid); //Sees ID
            Service.getOrderbyorderid ($scope.orderid )

            .success(function (response) {
                $scope.ordertest = []
                $scope.ordertest = response.data;
                console.log($scope.ordertest ); //Undefined
            })
        };

Question

Can someone help me in calling the controller right so I can call the api with a specific orderid?

Error I am getting

I am getting an undefined when I

console.log($scope.ordertest), 

but I see the id when I

console.log($scope.orderid);

Solution

  • You should use .then rather than .success. From the angular docs:

    The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

    The .success method destructs the response object for .then:

    Service.getOrderbyorderid($scope.orderid)
    // .success(function (data) {
       .then(function (response) {
         $scope.ordertest = response.data;