我已多次看过这个问题,但我无法弄清楚为什么我的一个控制器功能(控制器1)工作正常而一个(控制器2)没有。
控制器1:
angular.module('app').controller('MyCtrl1',function($scope,MyFactory)) {
//This function works great
MyFactory.deleteItem(item.id).then(function(response) {
//woot woot I am here and I am fine
});
}); //end controller 1
控制器2:
angular.module('app').controller('MyCtrl2',function($scope,MyFactory)) {
//Function #2 that doesn't work ... 'then' is undefined
MyFactory.createItem(item).then(function(response) {
//booo hooo I never get here and I am definitely not fine
});
}); //end controller 2
工厂:
.factory("MyFactory", function($http) {
var service = [];
service.deleteItem = function(itemId) {
return $http({
method: "delete",
url: "http://www.example.com",
params: //valid params go here
}).then(function(response) {
console.log("DELETING!!!!");
return response.data;
});
}
service.createItem = function(post) {
return $http({
url: '?create',
method: 'post',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: payload //an object
}).then(function(response){
console.log(response.data); //we are fine here. there is a valid response
return response.data;
});
}
return service;
}); //end factory
执行“createItem
”时抛出的错误是“Cannot read property 'then' of undefined
”我缺少什么?
答案 0 :(得分:3)
您错过了createItem
声明中的回复:
service.createItem = function(post) {
return $http({
url: '?create',
method: 'post',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: payload //an object
}).then(function(response){
console.log(response.data); //we are fine here. there is a valid response
return response.data;
});
}
没有它,就没有你不能链接.then
的返回值(未定义)。
答案 1 :(得分:-2)
如果您没有返回$http
这样的用途:
$http({
url: '?create',
method: 'post',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: payload //an object
}).$promise.then(function(response){
console.log(response.data);
return response.data;
});