我試圖從此服務獲取天氣信息,並使用AngularJS庫填充動態數據的html。使用Angular JS激活API
http://api.openweathermap.org/data/2.5/weather?q=Riyadh,ksa&appid=a809c777d6813b6b0905a9a7bf1a8399
我應該放在一個腳本標記此鏈接?如果是的話,我可以如何使用它與AngularJS。這是我第一次使用api和AngularJS,我看了很多教程,但沒有一個像這個api鏈接。
我試圖從此服務獲取天氣信息,並使用AngularJS庫填充動態數據的html。使用Angular JS激活API
http://api.openweathermap.org/data/2.5/weather?q=Riyadh,ksa&appid=a809c777d6813b6b0905a9a7bf1a8399
我應該放在一個腳本標記此鏈接?如果是的話,我可以如何使用它與AngularJS。這是我第一次使用api和AngularJS,我看了很多教程,但沒有一個像這個api鏈接。
假設你使用的是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調用成功,您可以通過$scope
變量在html視圖中的任何地方訪問它。
如果你需要你的API調用是動態的,那麼你可以根據你的需求在函數中構造API url字符串。我建議你閱讀this。
我編輯了我的答案以包含html視圖 –
我錯誤地使用了響應而不是response.data-現在它適用於我。我更新了代碼。你可以試試這個嗎? –
這是一個使用相同代碼的jsfiddle https://jsfiddle.net/7nnqL7vL/2/ –
你應該做這樣的事情
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看看我的例子..這會幫助你獲得一個好主意..希望這有助於..乾杯 –
您也可以作出這樣
$http.get(url)
.then(function(response) {
// Request completed successfully
}, function(x) {
// Request error
});
理念服務是您收到你的數據來自api終點,並顯示在你的應用程序中。這些可能在角度版本1,2,4上有所不同。但是您可以閱讀api文檔http://openweathermap.org/current以瞭解如何獲取數據。然後,您可以在網上找到其他人使用角度顯示公開天氣數據的示例。但你應該熟悉角度層次結構 – k185