как передать переменную из области видимости контроллера на фабрику - PullRequest
2 голосов
/ 07 июня 2019

Поэтому я хочу, чтобы пользователь мог изменять 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 Ответ

2 голосов
/ 07 июня 2019

Чтобы достичь ожидаемого результата, используйте нижеприведенную опцию
1. Завершение возврата фабрики в другую функцию, передавая cityName
2. Используйте значение $ scope.name в качестве значения параметра, т.е. getWeatherJSON ($ scope.cityName)

Быстрый способ выполнения запроса GET.

Фабрика:
app.factory("getWeatherJSON", ['$http', function ($http) { return function(cityName){ return $http.get(<code>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) }) }])

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...