【问题标题】:Activating API using Angular JS使用 Angular JS 激活 API
【发布时间】:2018-01-22 02:29:20
【问题描述】:

我正在尝试从此服务获取天气信息,并使用 AngularJS 库用动态数据填充 html。

http://api.openweathermap.org/data/2.5/weather?q=Riyadh,ksa&appid=a809c777d6813b6b0905a9a7bf1a8399

我应该将此链接放在脚本标签中吗?如果是,我如何将它与 AngularJS 一起使用。这是我第一次使用 api 和 AngularJS,我看了很多教程,但没有一个像这个 api 链接。

【问题讨论】:

  • 这个想法是您从 api 端点接收数据并将它们显示在您的应用程序中。这些可能在角度版本 1、2、4 上有所不同。但您可以阅读 api 文档 openweathermap.org/current 了解如何获取数据。然后你可以在网上找到一些其他人使用角度显示开放天气数据的示例。但是你应该熟悉 Angular 层次结构

标签: html css angularjs api


【解决方案1】:

你应该这样做

app.controller("testController", function($scope,testService){
            testService.getData ()
                .then(function (response) {
                    $scope.testData = response.data;
                    // handle valid reponse

                },
                function(error) {
                    //handel error
                });
        }

始终处理错误。

你也应该创建一个服务

angular.module('myApp')
  .service('testService', function ($http) {

   this.getData = function () {
      var endpoint = "url/";
      return $http({
        method: 'get',
        url:  endpoint
      });
    };

}

查看this简单应用程序的详细视图

【讨论】:

  • @R_95 看看我的例子 .. 这会帮助你得到一个好主意 .. 希望这会有所帮助 .. 干杯
【解决方案2】:

假设您使用的是 GET API,您可以使用 $http.get 来调用您的 API

    <script 
 src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
    </script>
    <div ng-app="weatherApp" ng-controller="weatherCtrl">
    <button ng-click="GetWeatherInfo()">Get weather data</button>
    Temperature: {{weatherdata.main.temp}}
    </div>

    <script>
    var app = angular.module('weatherApp', []);
    app.controller('weatherCtrl', function($scope,$http) {
        $scope.GetWeatherInfo= function(){
           $http.get("http://api.openweathermap.org/data/2.5/weather?
                      q=Riyadh,ksa&appid=a809c777d6813b6b0905a9a7bf1a8399")
            .then(function(response) {
              $scope.weatherdata= response.data;
           }); 
        }
    });
    </script>

这将在单击获取天气数据按钮时调用您的 API。 API 调用成功后,您可以在 html 视图中的任何位置使用 $scope 变量访问它。

如果您需要动态 API 调用,则可以根据您的要求在函数内构造 API url 字符串。我建议你阅读this

【讨论】:

  • 我错误地使用了响应而不是 response.data-它现在对我有用。我已经更新了代码。你可以试试这个吗?
【解决方案3】:

你也可以做这样的服务

$http.get(url)
.then(function(response) {
// Request completed successfully
}, function(x) {
// Request error
 });

【讨论】:

    猜你喜欢
    • 2022-09-30
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多