Я разрабатываю приложение простой погоды в угловом, в котором у меня два контроллера. Первый контроллер содержит форму, содержащую два входных города и страны, а кнопка поиска - ng-click=weathercheck()
weatherapp.controller('mainController', ['$scope', 'commonservice', '$location', '$rootScope', function ($scope, commonservice, $location, $rootScope) {
$scope.weathercheck = function (city, country) {
commonservice.getweather(city, country);
};
}])
здесь второй контроллер и код маршрута
weatherapp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/main', {
templateUrl: 'main.htm',
controller:'mainController'
})
.when('/result', {
templateUrl: 'result.htm',
controller: 'ResultController'
})
.otherwise({
redirectTo:'/main'
})
}])
weatherapp.controller('ResultController', ['$scope', 'commonservice', '$rootScope', function ($scope, commonservice, $rootScope) {
здесь я хочу получить точные данные из функции api call getdata снова позвонить в службу, так как здесь у меня нет значений в городе и стране, они дают мне только данные по умолчанию
$scope.place = commonservice.getweather(data);
getdata();
function getdata() {
commonservice.getweather().then(function (data) {
$scope.place = data;
})
}
}])
метод вызова метода проверки погоды в службе, который имеет api call
function getweather(city, country) {
var deferred = $q.defer();
return $http.get('http://api.openweathermap.org/data/2.5/forecast?q='+city+','+country +'&cnt=5&units='+unit)
.success(function (data) {
console.log(data);
weatherresult = data;
deferred.resolve(data);
return weatherresult;
// $location.path('/result');
})
.error(function (err) {
console.log('Error getting results');
// deferred.reject(err);
})
return deferred.promise;
}
return {
getweather: getweather
};
<script type="text/ng-template" id="main.htm">
this is first controller that contain form and search button
</script>
<script type="text/ng-template" id="result.htm">
this is the second controller where i want to show result
</script>
я застрял здесь в течение двух дней, так как это мое первое угловое приложение
success
обратного вызова не возвращается к другому then
. Также у вас было 2 return
в функции getWeather()
Попробуй это:
function getweather(city, country) {
return $http.get('http://api.openweathermap.org/data/2.5/forecast?q=' + city + ',' + country + '&cnt=5&units=' + unit)
.then(function (response) {
console.log(response.data);
return response.data;
}).catch(function (err) {
console.log('Error getting results');
});
}
return {
getweather: getweather
};