首页 > 解决方案 > 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?

标签: javascriptangularjs

解决方案


推荐阅读