Page 429 - AngularJS权威教程
P. 429
31.9 使用 Wundergroud 的天气 API 409
angular.module('myApp', []) 19
.provider('Weather', function() {
})
在这个方法内,需要定义一个$get()函数,该函数返回可用于这个服务中的方法。要配置这 20
个服务,还需要一个可以在配置中设置API密钥的方法。而这些方法都应该在$get()函数的作用
域外部。
21
.provider('Weather', function() {
var apiKey = "";
22
this.setApiKey = function(key) {
if(key) this.apiKey = key;
}; 23
this.$get = function($http) {
return {
// 服务对象 24
}
}
}) 25
使用这段小巧的代码,现在,我们可以将Weather服务注入到.config()函数中,然后使用你
的Wunderground API密钥来配置这个服务。 26
当Angular碰到使用.provider() API方法创建的提供者时,它会创建一个可注入对象
[Name]Provider。这是一个将会注入到配置函数中的对象: 27
// .provider('Weather', function() {
// ...
// }) 28
.config(function(WeatherProvider) {
WeatherProvider.setApiKey('YOUR_API_KEY');
}) 29
// .controller('MainController', function($scope, $timeout) {
// ...
Wunderground的API要求我们将这个API密钥传递给请求的URL。为了将API密钥传递给每个 30
请求,还需要创建一个生成这个URL的函数。
31
var apiKey = "";
// ...
this.getUrl = function(type, ext) {
return "http://api.wunderground.com/api/" + 32
this.apiKey + "/" + type + "/q/" + ext + '.json';
};
33
现在,我们可以创建API来调用Weather服务,帮我们从Wunderground的API中获取最新的预
测数据。
34
我们将会创建自己的、可以用来在视图中解析数据的promise,因为我们只希望从API调用中
返回相关的结果:
35
this.$get = function($q, $http) {
var self = this;
return {
getWeatherForecast: function(city) { 36