【问题标题】:How to pass param from controller to service in AngularJs如何将参数从控制器传递到AngularJs中的服务
【发布时间】:2017-07-03 20:28:37
【问题描述】:

我目前正在做一个项目来帮助我更好地理解 angularjs!我目前坚持如何将参数从控制器传递给服务。

在我的程序中,当用户键入输入并单击按钮时,我创建了一个名为“GetForecastByLocation”的函数。从那里我想接受他们的输入,然后将其传递给 service.js 中的 http 调用。

最初,$http.get 位于 API url 的一个长长的巨大字符串中,但我搜索了一下,似乎我应该在尝试更改字符串的一部分时使用参数。截至目前,我知道参数是硬编码到特定城市的,但我想接受新的输入并将 vm.city 的值传递给 $http.get 调用。

如果有人可以提供帮助,我将不胜感激。谢谢!

controller.js

    var app = angular.module('weatherApp.controllers', [])
    app.controller('weatherCtrl', ['$scope','Data',
        function($scope, Data) {

        $scope.getForecastByLocation = function(myName) {
            $scope.city = myName;
            Data.getApps($scope.city);},

        Data.getApps(city)
        .then(function(data)){
        //doing a bunch of things like converting units, etc
        },
        function(res){
            if(res.status === 500) {
            // server error, alert user somehow
        } else { 
            // probably deal with these errors differently
        }
        }); // end of function
}]) // end of controller 

service.js

.factory('Data', function($http, $q) {
       var data = [],
           lastRequestFailed = true,
           promise;
       return {
          getApps: function() {
             if(!promise || lastRequestFailed) {
            promise = $http.get('http://api.openweathermap.org/data/2.5/weather?',{
              params: {
                q: Tokyo,
              }
            })
            .then(function(res) {
                lastRequestFailed = false;
                data = res.data;
                return data;
            }, function(res) {
                return $q.reject(res);
            });
         }
         return promise;
      }
   }
});

【问题讨论】:

  • 为什么不给getApps加个参数呢?工厂看起来像getApps: function(city){ ...,呼叫站点像Data.getApps($scope.city)
  • 嗨@wilusdaman!抱歉,我对 angularjs 很陌生。如果您可以显示完整的代码/详细说明,我将不胜感激!谢谢! //在你的代码中,我还需要参数吗?如果我理解正确的话,来自 function(city) 的值填写 q: city,对吗?

标签: javascript angularjs openweathermap


【解决方案1】:

将参数传递给工厂方法与将参数传递给普通的旧函数没有什么不同。

首先,设置getApps接受一个参数:

.factory('Data', function($http, $q){
    // ...
    return {
        getApps: function(city){
            promise = $http.get(URL, {
                params: {q: city}
            }).then( /* ... */ );
            // ...
            return promise;
        }
    };
});

然后将你的论点传递给它:

$scope.getForecastByLocation = function(myName) {
    $scope.city = myName;
    Data.getApps($scope.city);
}

【讨论】:

  • 谢谢!我知道这会起作用,因为我尝试传入一个参数并且它改变了。我希望这可以问,但我有后续问题。所以早些时候,我没有显示我的整个 controller.js 代码,现在我已经更新了它,但是单击按钮后调用的函数不会将城市发送到服务。我之所以这么想是因为我可能在控制器中放置了 getForecastbyLocation 。我认为它在错误的地方,但我不知道该放在哪里。你有什么建议/建议吗?再次感谢您!
  • 你的ng-click是什么样的?
  • 目前看起来像这样<md-button class="md-raised" ng-click="getForecastByLocation(myName)">SUBMIT</md-button>
  • 明白了。我认为您需要getForecastByLocation(city),因为$scope.city 存在而$scope.myName 不存在(或者从您共享的代码看来就是这样)
  • $scope.getForecastByLocation 在控制器中的位置是否重要?或者代码中显示的原始位置可以吗?
【解决方案2】:

这就像为函数的上下文变量设置一个值。

Services.js

服务的简单示例。

.factory('RouteService', function() {
    var route = {}; // $Object

    var setRoute_ = function(obj)
    {
        return route = obj;
    };

    var getRoute_ = function()
    {
        if(typeof route == 'string')
        {
            return JSON.parse(route);
        }

        return null;
    };

    return {
        setRoute: setRoute_,
        getRoute: getRoute_
    };
})

Controllers.js

服务使用简单示例:

.controller('RoutesCtrl', function ($scope, RouteService) {
    // This is only the set part.
    var route = {
        'some_key': 'some_value'
    };

    RouteService.setRoute(route);
})

【讨论】:

    猜你喜欢
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 2016-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多