2016-06-14 9 views
0

На линии 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; 

    }; 

}) 
+1

Удалить $ Q от параметров функции SubmitForm – dtkaias

ответ

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); 
    }); 
};