将参数传递给控制器​​的异步服务方法

时间:2016-01-04 10:00:33

标签: angularjs angularjs-service

我是angularjs的新手,所以我很难将一个参数从控制器传递给service方法。

我的控制器看起来像这样:

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;
    });
});

服务方式:

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;
});

这段代码运行正常。现在我想传递变量' server'从控制器用于服务而不是链接。知道怎么做吗?如何在服务函数调用中使用多个变量?

1 个答案:

答案 0 :(得分:2)

更新的代码介于** **

之间
 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;
});