$http連線取得JSON資料
$http實際上是發出http要求,進而取得回應資料。如果格式是JSON,在JavaScript中便可直接使用,其他格式則不一定。$http連線使用方式如下:
$http.get("http://url/service", { params: { "key1": "value1", "key2": "value2" } }) .success(function(response) { // 處理http回應資料; response為回傳資料 }) .error(function(err) { // 連線錯誤 });另一種寫法則是:
$http.get("http://url/service", { params: { "key1": "value1", "key2": "value2" } }) .then(function(response) { // 建立天氣資料模型變數,response.data為回傳資料 }, function(err) { // 連線錯誤 });兩者有所差別,可參考此討論串。在此建議用
.then(function(resp),function(err))
以open weather map即時天氣資料為例,其api格式是:
http://api.openweathermap.org/data/2.5/weather?q=Taipei因此對應的程式碼為:
$http.get("http://api.openweathermap.org/data/2.5/weather", { params: { "q": "Taipei"} }) .then(function(response) { // 建立天氣資料模型變數,response.data為回傳資料 }, function(err) { // 連線錯誤 });有了$http連線服務,取得天氣即時資訊變得非常簡單。
即時天氣資料呈現
以前文Hybrid Apps開發系列之4.4:多頁面App程式 (天氣app-非線上版)天氣概況頁面為基礎,並在controller處加上$http連線,便可呈現即時天氣資料。此處以單一頁面為例,將天氣概況頁面的程式碼直接放入index.html中,並加入一個按鈕,程式碼如下:
- <body ng-app="starter">
- <ion-header-bar class="bar-stable">
- <h1 class="title">天氣概況:Json版</h1>
- </ion-header-bar>
- <ion-content ng-controller="controller">
- <button ng-show="!show" ng-click="getData()">取得資料</button>
- <div class="list card" ng-show="show">
- <div class="item">
- <h2>City of {{weather.name}}</h2>
- </div>
- <div class="item item-avatar">
- <img src="{{img_base_url + weather.weather[0].icon + '.png'}}">
- <h2>{{weather.main['temp'] - 273.15| number:1}}°C</h2>
- <h2>{{(weather.dt)*1000 | date:'yyyy-MM-dd HH:mm:ss'}}</h2>
- </div>
- <div class="item">
- <div class="row">
- <div class="col">濕度</div>
- <div class="col">{{weather.main.humidity}}%</div>
- </div>
- <div class="row">
- <div class="col">風速</div>
- <div class="col">{{weather.wind.speed}}哩/秒</div>
- </div>
- </div>
- </div>
- </ion-content>
- </body>
- 第5行:由於是單一頁面,故直接在<ion-content>設定處理此區塊的controller。
- 第6行:加入按鈕,點選之後呼叫getData()取得資料,同時隱藏按鈕。
- 第7行:ng-show的設定讓區塊先隱藏起來,取得資料後再呈現。
- [...略...]
- .controller('controller', function ($scope, $http) {
- $scope.show = false;
- $scope.img_base_url = image_base_url;
- $scope.getData = function () {
- $http.get("http://api.openweathermap.org/data/2.5/weather", {params: {"q": "Taipei"}})
- .then(function (resp) {
- $scope.weather = resp.data;
- $scope.show = true;
- }, function (err) {
- alert("Oops!");
- })
- }
- })
- var image_base_url = "http://openweathermap.org/img/w/"; // open weather api icon
- 第2行:定義controller時要加入$http模組。
- 第3行:$scope.show用來控制按鈕與天氣概況的顯示狀態。
- 第5-14行:getData()定義。
沒有留言:
張貼留言