【发布时间】: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