AngularJS 1.6的所有文档都非常模糊。每个人都有关于如何执行$ http.get请求的教程,但没有关于如何正确设置版本1.6的$ http.post请求的内容。
我要做的就是设置一个控制器,为我的迷你项目提供功能,允许用户在主页上的输入框中键入他/她的城市,并在他们提交信息时他们的预测将显示在预测页面上。因此,理论上,控制器会将数据“POST”到URL中,以便能够从Open Weather API检索信息。路线和其他一切工作正常......我只需要帮助这个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>
答案 0 :(得分:0)
以下是使用$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>