代码之家  ›  专栏  ›  技术社区  ›  playerone

从控制器向异步服务方法传递参数

  •  0
  • playerone  · 技术社区  · 9 年前

    我是angularjs的新手,所以我很难从控制器向服务方法传递参数。

    我的控制器如下所示:

    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 回复  |  直到 9 年前
        1
  •  2
  •   Ganesh Karamala    9 年前

    更新的代码介于**之间**

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