Javascript 如何将变量从控制器范围传递到工厂

Javascript 如何将变量从控制器范围传递到工厂,javascript,angularjs,Javascript,Angularjs,因此,我希望用户能够更改此服务使用的cityName: app.factory("getWeatherJSON", ['$http', function ($http) { return $http.get(`https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=8c644b89f214d6bee6c2123faabfb05&units=metric`) .then(func

因此,我希望用户能够更改此服务使用的cityName:

app.factory("getWeatherJSON", ['$http', function ($http) {
    return $http.get(`https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=8c644b89f214d6bee6c2123faabfb05&units=metric`)
        .then(function (data) {
            return data;
        })
        .then(null, function (err) {
            return err;
        });
}]);
这是我的控制器(cityName的来源):

我尝试在服务中使用$scope.cityName,但没有成功,如下所示:

return $http.get(`https://api.openweathermap.org/data/2.5/weather?q=${$scope.cityName}&appid=8c644b89f214d6bee6c2123faabfb05&units=metric`)

要达到预期效果,请使用下面的选项
1.在另一个传递cityName的函数中包装工厂返回
2.使用$scope.name值作为参数值,即getWeatherJSON($scope.cityName)

执行GET请求的快捷方式方法

工厂:
app.factory(“getWeatherJSON”,['$http',函数($http){
返回函数(cityName){
返回$http.get(
https://api.openweathermap.org/data/2.5/weather? q=:cityName&appid=8C644B89F214D6C2123FAABFB05&units=metric

} }]);

控制器:
app.controller(“mainController”),[“$scope”,“getWeatherJSON”,函数mainController($scope,getWeatherJSON){
$scope.cityName=“里约热内卢”;
getWeatherJSON($scope.cityName).then(函数(数据){
const weatherData=data.data;
控制台日志(天气数据)
})

}])

为什么要将错误响应转换为已履行的承诺?为什么要将错误响应转换为已履行的承诺?谢谢@georgeawg,我已经更新了我的答案,我只是重复使用了相同的代码并修改了我的changesthanks@NagaSaiA,但我遇到了错误:无法读取未定义的
app.factory的“then”属性(“getWeatherJSON”,['$http',函数($http){返回函数(cityName){$http.get(”https://api.openweathermap.org/data/2.5/weather?q=“+cytyName+”&appid=8c644b89f214d6bee6c24aa4faabfb05&units=metric“}]);app.controller(“mainController”、[“$scope”、“getWeatherJSON”、函数mainController($scope、getWeatherJSON){$scope.cityName=“London”;getWeatherJSON($scope.cityName)。然后(函数(数据){console.log(数据)}])
谢谢你,伙计。我终于找到了答案。你的代码在wrap函数中只缺少了第二个返回,就在$http.get之前
return $http.get(`https://api.openweathermap.org/data/2.5/weather?q=${$scope.cityName}&appid=8c644b89f214d6bee6c2123faabfb05&units=metric`)