我已经使用 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;
});
}
数据值设置为未定义。
我遗漏了一些东西,请帮助找出错误。
最佳答案
解决方案:
datacontext 中的 getFunctions 函数应返回 $http Promise 对象,如下所示:
function getFunctions() {
return $http.get('https://api.github.com/users/google/repos')
.error(function (data, status, headers, config) {
alert('error ! : ' + status);
});
}
并且在 Controller 中,您可以使用返回的json对象,如下所示:
function getRepos() {
return datacontext.getRepos().then(function (httpResult) {
vm.repos = httpResult.data;
});
}
关于json - 在 Hot Towel Angular 数据上下文中使用 return $q.when,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20914280/