Page 430 - AngularJS权威教程
P. 430
410 第 31 章 构建 Angular Chrome 应用
var d = $q.defer();
$http({
method: 'GET',
url: self.getUrl("forecast", city),
cache: true
}).success(function(data) {
// Wunderground API返回
//嵌套在forecast.simpleforcast属性内的forecasts对象
d.resolve(data.forcast.simpleforcast);
}).error(function(err) {
d.reject(err);
});
return d.promise();
}
};
}
现在,我们可以将这个Weather服务注入到控制器中,然后在控制器中调用getWeather
Forecase()方法以及响应promise,而不是处理API的复杂度。
回到MainController:现在可以注入Weather服务,然后在作用域上设置其结果:
.controller('MainController',
function($scope, $timeout, Weather) {
// ...
$scope.weather = {};
// 暂时使用硬编码的San_Francisco
Weather.getWeatherForecast("CA/San_Francisco")
.then(function(data) {
$scope.weather.forcast = data;
});
//...
要查看视图中调用这个API的结果,需要更新tab.html。出于调试的目的,这里先在一个<pre>
标签内使用json过滤器,效果如图31-7所示。
<div id="forecast">
<pre>{{ weather.forecast | json }}</pre>
</div>
图31-7 调用天气API进行调试
这里可以看到视图已经使用最新的天气数据更新了,现在我们来创建一个更优雅的视图。