【发布时间】:2015-04-19 04:13:06
【问题描述】:
我在尝试使用 angularjs 中的工厂和控制器设置一个相当简单的调用时遇到了问题。我一直在尝试按照 John Papa 和 Todd Motto 的风格指南进行设置。
首先我使用 2 个模块
(function(){
'use strict';
angular.module('app',[
'app.core',
'app.property'
]);
})();
在 'app.core' 我定义了工厂
(function(){
'use strict';
angular.module('app.core')
.factory('dataservice',dataservice);
dataservice.$inject = ['$http','$q'];
function dataservice($http,$q) {
var service = {
getListing: getListing
};
return service;
function getListing() {
var def = $q.defer;
$http.get("http://acme.com/property/1?format=json")
.success(function(data){
service.getListing = data;
def.resolve(data);
});
return def.promise;
}
}
})();
在“app.property”中我定义了控制器
(function(){
'use strict';
angular.module('app.property')
.controller('PropertyCtrl',PropertyCtrl);
PropertyCtrl.$inject = ['dataservice'];
function PropertyCtrl(dataservice) {
var vm = this;
vm.listings = [];
activate();
function activate() {
return getListing().then(function(){});
}
function getListing(){
return dataservice.getListing().then(function(data){
vm.listings = data;
console.log("data is");
console.log(data);
return vm.listings;
});
}
}
})();
我在控制台输出中得到的错误是
错误:dataservice.getListing(...) 未定义,除非我在 chrome 中检查数据服务时可以看到
我收到的进一步消息
TypeError: Cannot read property 'then' of undefined
TypeError: def.resolve is not a function
尽管有这些错误,远程调用仍能正常返回 json。
希望有棱角的人知道我哪里出错了。
【问题讨论】:
标签: angularjs