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搜索被拉出的网页的数据?
答案 0 :(得分: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>
&#13;