Вся документация для AngularJS 1.6 чрезвычайно неоднозначна. У всех есть обучающие программы для того, как выполнять запросы http.get, но ничего о том, как правильно настроить $ http.post запросы для версии 1.6.
Все, что я пытаюсь сделать, это настроить контроллер, который дает моему мини-проекту функциональность, позволяющую пользователю вводить свой город в поле ввода на главной странице и, когда они его подают, информация для их прогноза появится на странице "Прогноз". Итак, теоретически, контроллер будет "POST" данных в URL-адрес, чтобы иметь возможность извлекать информацию из API Open Weather. Маршруты и все остальное отлично работают... Мне нужна помощь только для этого метода POST.
Мои извинения за мой код выглядят непонятно. Я только что опубликовал то, что у меня было.
В целом, у кого-то есть ДЕЙСТВИТЕЛЬНО хорошие ресурсы для документации по AngularJS 1.6?
(function () {
'use strict';
// MODULE
angular.module("WeatherApp", ['ngRoute', 'ngResource', 'http'])
// ROUTES
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'templates/home.html',
controller: 'homeCtrl'
})
.when('/forecast', {
templateUrl: 'templates/forecast.html',
controller: 'forecastCtrl'
});
})
// SERVICES
.service('cityService', function () {
this.city = "Chicago";
})
// CONTROLLERS
.controller("homeCtrl", function ($scope, cityService) {
$scope.city = cityService.city;
$scope.$watch('city', function () {
cityService.city = $scope.city;
});
})
.controller("forecastCtrl", function ($scope, $http, cityService) {
$scope.city = cityService.city;
$http.post("http://api.openweathermap.org/data/2.5/forecast/daily", {q: $scope.city, cnt: 2, appid: "8a3dfe91838e8409da30958ed6b68932"}).then(function (data) {
console.log();
});
});
})();
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h4>Forecast by City</h4>
<div class="form-group"><input ng-model="city" type="text" class="form-control"></div>
<a href="#!/forecast" class="btn btn-primary">Get Forecast</a>
</div>
</div>
Ниже приведен пример использования $http.post
. API возвращается с ошибкой, и я надеюсь, что вы сможете это расследовать.
angular
.module('MyApp', []);
angular
.module('MyApp')
.controller('ForecastController', [
'$scope',
'$http',
function($scope,
$http) {
$scope.vm = {
city: 'Newyork',
errorMessage: ''
}
$scope.getForecast = function() {
var vm = $scope.vm;
console.log('Getting forecast for ' + vm.city + ' city');
/*$http.get("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1")*/
$http.post("http://api.openweathermap.org/data/2.5/forecast/daily", {
q: vm.city,
cnt: 2,
appid: "8a3dfe91838e8409da30958ed6b68932"
})
.then(function(data) {
console.log('Got forecast successfully.');
}, function(error) {
var message = 'There was an error getting forecast';
console.log(message);
console.log(error);
vm.errorMessage = message;
});
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<style>
.item-row {
margin-bottom: 10px;
}
.item-row:last-child {
margin-bottom: 0;
}
</style>
<div ng-app="MyApp">
<div ng-controller="ForecastController">
<div class="item-row" ng-show="vm.errorMessage">
{{vm.errorMessage}}
</div>
<div class="item-row">
<input type="text" ng-model="vm.city" />
</div>
<div class="item-row"> You entered: {{vm.city}}</div>
<div class="item-row">
<button ng-click="getForecast()">Get Forecast</button>
</div>
</div>
</div>
ng-click
Get Forecast (или кнопки, используемой в качестве ссылки), чтобы вызвать метод, определенный в$scope
и в этом методе вам нужно будет использовать$http.post
.$http.post
выглядит хорошо. Вам не нужно несколько контроллеров, чтобы сделать это.