javascript - Angularjs 中的 API 调用
问题描述
假设有 3 个 API。每个 API 执行完全相同的任务(为您提供天气详细信息),但具有不同的端点,如下所示:
API 1:只能用于印度。有命名的方法requestWeather(), requestWeatherDataForWeek()
API 2:只能用于美国。有命名的方法sendRequest(), weatherDataForWeek()
API 3:只能用于英国。具有名为getWeather(), getWeatherDataForWeek()
.
使用下拉菜单选择国家。
一个。根据国家选择API。API选择是程序化的,将根据用户选择的国家来决定。
湾。编写您的代码,以便在不干扰业务逻辑的情况下使用任何 API。
C。可以发送的请求数量必须有限制。如果不是,则抛出错误。的请求超过限制。
d。它不需要 HTTP 调用或 API。只需使用指定的方法为 API 创建一个包装器并返回一些虚拟值。
weatherApp.config(function ($stateProvider,$urlRouterProvider) {
$stateProvider
.state('/', {
templateUrl: 'home.html',
controller: 'homeController'
})
.state('forecast', {
url:"/forecast",
templateUrl: 'forecast.html',
controller: 'forecastController'
})
$urlRouterProvider.otherwise("/");
});
weatherApp.service('cityService', function() {
this.city = "New York, NY";
});
weatherApp.controller('Controller',['$scope','$state',function($scope,$state){
$scope.clicked=function(){
$state.go('forecast');
};
}]);
weatherApp.controller('homeController', ['$scope', 'cityService', function($scope, cityService) {
$scope.city = cityService.city;
$scope.$watch('city', function() {
cityService.city = $scope.city;
});
}]);
weatherApp.controller('forecastController', ['$scope', '$resource', '$routeParams', 'cityService', function($scope, $resource, $routeParams, cityService) {
$scope.city = cityService.city;
$scope.days = $routeParams.days || 2;
$scope.weatherAPI = $resource("http://api.openweathermap.org/data/2.5/forecast/daily", { callback: "JSON_CALLBACK" }, { get: { method: "JSONP" }});
$scope.weatherResult = $scope.weatherAPI.get({ q: $scope.city, cnt: $scope.days });
$scope.convertToFahrenheit = function(degK) {
return Math.round((1.8 * (degK - 273)) + 32);
}
$scope.convertToDate = function(dt) {
return new Date(dt * 1000);
};
}]);
我尝试过这种方式。我们如何创建一个包装器而不包含 HTTP 和 API?
解决方案
推荐阅读
- asp.net-mvc - ASP.NET MVC 在新窗口中打开文件
- database - 如何使用 PostgreSQL (psql) 在 Google Cloud Platform 上的 Shell 内更改数据库?
- jenkins - 在哪里设置 -Dorg.jenkinsci.plugins.durabletask.BourneShellScript.HEARTBEAT_CHECK_INTERVAL=300
- php - 提高联系表格的安全性
- docker - 如何选择性地将日志文件转发到 Splunk 中的特定索引?
- generics - 在结构和功能块中使用泛型
- r - 如何使用分隔符的用户列表拆分文本但输入不匹配的 NA 并维护列
- java - 在 Java 中以两种方式将月份添加到日期会产生两种不同的结果(闰年哲学?)
- swift - 如果我附加到函数内的全局数组,为什么要从函数返回一个项目?
- batch-file - 行与批次的比较