2016-11-19 103 views
-1
app.factory('WeatherApi', function($http) { 
    var obj = {}; 

    obj.getLoc = function() { 
     return $http.jsonp("http://ipinfo.io/json?callback=JSON_CALLBACK"); 
    }; 

    obj.getCurrent = function(city) { 
     var api = "http://api.openweathermap.org/data/2.5/weather?q="; 
     var units = "&units=metric"; 
     var appid = "&APPID=061f24cf3cde2f60644a8240302983f2" 
     var cb = "&callback=JSON_CALLBACK"; 

     return $http.jsonp(api + city + units+ appid + cb); 
    }; 
    return obj 
}); 

有人可以解釋這塊代碼的作用嗎?我不明白所有不同的變量是什麼。 obj.getLoc到底做了什麼?這是否意味着它創建了一個函數。那麼他們都會在最後形成一個鏈接,然後json搜索被拉起的網頁的數據?Javascript角度工廠解釋

+0

這是兩個函數中的角應用程序的其餘部分是可用的。他們必須由應用程序的其他部分調用。閱讀[關於$ http的角度文檔](https://docs.angularjs.org/api/ng/service/$http),你就會明白這些函數的作用:'getLoc' - 對ipinfo進行AJAX調用,它是提供有關瀏覽器IP地址的地理位置數據的Web服務。 'getCurrent'嘗試對openweathermap.org進行AJAX調用,獲取有關給定城市的天氣信息。 –

回答

0

這段代碼定義了一個在您的應用程序內重用的服務。

示例用法:

var app = angular.module('app', []); 
 

 
app.factory('WeatherApi', function($http) { 
 
    var obj = {}; 
 

 
    obj.getLoc = function() { 
 
    return $http.jsonp("http://ipinfo.io/json?callback=JSON_CALLBACK"); 
 
    }; 
 

 
    obj.getCurrent = function(city) { 
 
    var api = "http://api.openweathermap.org/data/2.5/weather?q="; 
 
    var units = "&units=metric"; 
 
    var appid = "&APPID=061f24cf3cde2f60644a8240302983f2" 
 
    var cb = "&callback=JSON_CALLBACK"; 
 

 
    return $http.jsonp(api + city + units + appid + cb); 
 
    }; 
 
    return obj 
 
}); 
 

 
app.controller('someCtrl', function(WeatherApi) { 
 
    var vm = this; 
 
    WeatherApi.getLoc().then(function(response) { 
 
    vm.location = response.data; 
 
    console.log('Your location:' + JSON.stringify(vm.location)); 
 
    }) 
 
    WeatherApi.getCurrent('nyc').then(function(response) { 
 
    vm.nycWeather = response.data; 
 
    console.log('Weather in NYC:' + JSON.stringify(vm.nycWeather)); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="app" ng-controller="someCtrl as vm"> 
 
</div>

+1

謝謝,現在更有意義。我更好地理解這是如何工作的。 –