playerone
playerone

Reputation: 1127

Passing a parameter to async service method from controller

I am new to angularjs so I am struggling to pass a parameter to service method from controller.

My controller looks like this:

userControllers.controller('StartController', function(startService,$scope) {
    var server='http://localhost:8080/terminal/1';
    // Call the async method and then do stuff with what is returned inside our own then function
    startService.async().then(function(d) {
        $scope.message = d;
    });
});

Service method:

myService.factory('startService', function($http) {
    var startService = {
        async: function () {
            // $http returns a promise, which has a then function, which also returns a promise
            var promise = $http.get('http://localhost:8080/terminal/1').then(function (response) {
                // The then function here is an opportunity to modify the response
                console.log(response.headers('link'));

                // The return value gets picked up by the then in the controller.
                return response;
            });
            // Return the promise to the controller
            return promise;
        }
    };
    return startService;
});

And this code works fine. Now I want to pass variable 'server' from controller to be used in service instead of link. Any idea how to do that? How to use more than one variable in service function call?

Upvotes: 0

Views: 863

Answers (1)

Ganesh Karamala
Ganesh Karamala

Reputation: 513

Updated code is in between ** **

 userControllers.controller('StartController', function(startService,$scope) {
        var server='http://localhost:8080/terminal/1';
        // Call the async method and then do stuff with what is returned inside our own then function
        **startService.async(server).then(function(d) {**
            $scope.message = d;
        });
    });



myService.factory('startService', function($http) {
    var startService = {
        async: **function (server) {**
            // $http returns a promise, which has a then function, which also returns a promise
            var promise = **$http.get(server)**.then(function (response) {
                // The then function here is an opportunity to modify the response
                console.log(response.headers('link'));

                // The return value gets picked up by the then in the controller.
                return response;
            });
            // Return the promise to the controller
            return promise;
        }
    };
    return startService;
});

Upvotes: 2

Related Questions