【发布时间】:2014-01-03 23:01:33
【问题描述】:
我已经使用 Hot Towel Angular 模板创建了一个 Web 应用程序,并且我想向“datacontext”添加一个服务功能。
代码是:
(function () {
'use strict';
var serviceId = 'datacontext';
angular.module('app').factory(serviceId, ['common', '$http', datacontext]);
function datacontext(common, $http) {
var $q = common.$q;
var service = {
getFunctions: getFunctions
};
return service;
function getFunctions() {
var f = [];
$http({
method: 'GET',
url: 'https://api.github.com/users/google/repos',
contentType: 'application/json; charset=utf-8'
})
.success(function (data, status, headers, config) {
f = data;
console.log('f=*' + f + '*');
})
.error(function (data, status, headers, config) {
alert('error!');
});
return $q.when(f);
}
}
})();
我看到控制台显示了一些对象:
f=*[object Object],[object Object],[object O...
但是在我的 functionController.js 文件中使用它时:
function getFunctions() {
return datacontext.getFunctions().then(function (data) {
console.log('data=*' + data + '*');
return vm.functions = data;
});
}
数据的值设置为undefined。
我遗漏了一些东西,请帮助找出错误。
【问题讨论】:
-
您的
$q.when(f)只是将空数组[](即执行返回时f的当前值)包装到一个promise 中。然后立即使用此值解决此承诺,即使用 data=[] 调用您的 then-callback。 -
好的,我明白了,但是有什么解决方案可以使这项工作?
标签: json http angularjs hottowel q