在var deferred = $q.defer();
行
当我尝试使用以下代码提交简单表单时,我得到:TypeError: Unable to get property 'defer' of undefined or null reference
。
angular.module('app').controller('enrollCtl', function enrollCtl($q, $http)
{
// Using 'Controller As' syntax, so we assign this to the vm variable (for viewmodel).
var vm = this;
// Bindable properties and functions are placed on vm.
vm.applicantData = {
FirstName: "",
Comment: ""
};
vm.registerApplicant = function submitForm($q, $http)
{
console.log('posting data::' + vm.applicantData.FirstName)
var serverBaseUrl = "https://test.com/TestForm";
var deferred = $q.defer();
return $http({
method: 'POST',
url: serverBaseUrl,
data: vm.applicantData
}).success(function (data, status, headers, cfg)
{
console.log(data);
deferred.resolve(data);
}).error(function (err, status)
{
console.log(err);
deferred.reject(status);
});
return deferred.promise;
};
})
答案 0 :(得分:1)
您已将$q
和$http
两次作为参数声明,一次在您的控制器上,一次在您的功能上。这些模块只会被注入你的控制器,你的函数的参数(如果你没有任何东西调用函数,它们的值为undefined
)会影响它们。
请注意,您should not use $q.deferred
here anyway,只需返回$http
已经给您的承诺:
vm.registerApplicant = function submitForm() {
console.log('posting data::' + vm.applicantData.FirstName)
return $http({
// ^^^^^^
method: 'POST',
url: "https://test.com/TestForm",
data: vm.applicantData
}).success(function (data, status, headers, cfg) {
console.log(data);
}).error(function (err, status) {
console.log(err);
});
};