因此,我希望用户能够更改此服务使用的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来自何处):

app.controller("mainController", ["$scope", "getWeatherJSON", function mainController($scope, getWeatherJSON) {
    $scope.cityName = "Rio de Janeiro";
    getWeatherJSON.then(function (data) {
        const weatherData = data.data;
        console.log(weatherData)
    })
}])


我试图在服务内部使用$ 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', function ($http) { return function(cityName){ return $http.get(https://api.openweathermap.org/data/2.5/weather? q=:cityName&appid=8c644b89f214d6bee6c2123faabfb05&units=metric
    }
    }]);

控制器:
    app.controller("mainController", ["$scope", "getWeatherJSON", function mainController($scope, getWeatherJSON) { $scope.cityName = "Rio de Janeiro"; getWeatherJSON($scope.cityName).then(function (data) { const weatherData = data.data; console.log(weatherData) }) }])

关于javascript - 如何将变量从 Controller 范围传递到工厂,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56497817/

10-09 19:03