为什么在下面的 angularjs 示例中 $q 未定义?

Why is $q undefined in the following angularjs example?

在第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;

    };

})

您已将 $q$http 声明为参数两次,一次在您的控制器中,一次在您的函数中。这些模块只会被注入到你的控制器中,并且你的函数的参数(如果你什么都不调用函数,它们的值是 undefined)会影响它们。

注意你 should not use $q.deferred here anyway,只是 return $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);
    });
};