javascript - Angular 工厂函数抛出错误声称它不是 Controller 中的函数

标签 javascript angularjs rest

我以前见过几个这样的问题,但它们通常明显缺少注入(inject),希望我的问题不是这种情况。

作为我正在制作的应用程序的一部分,我正在尝试向服务器发出获取请求以返回模块列表。

Controller

app.controller('ModulesCtrl', ['$scope','modFact','quizIndexFactory', '$http', function($scope, $http, quizIndexFactory, modFact){

$scope.moduleSet;
$scope.status;

getModules();

function getModules(){
    modFact.getList()
        .then(function (response) {
            $scope.moduleSet = response.data;
        }, function (error) {
            $scope.status = 'unable to load modules in controller: ' + error.message;
        });
}

工厂

app.factory('modFact', ['$http', function($http){
var modFact = {};

modFact.getList = function() {
    console.log("success");
    return $http.get('http://localhost:3000/module');
};

return modFact;
}]);

但我得到指向 Controller 中函数调用的错误:

Error: modFact.getList is not a function

有什么想法吗?我遵循这篇博文提供的结构: http://weblogs.asp.net/dwahlin/using-an-angularjs-factory-to-interact-with-a-restful-service

最佳答案

似乎注入(inject) Controller 的参数顺序与您提供参数的顺序不匹配。在您的 Controller 中,名为 modFact 的实体实际上是 Angular 的 $http 服务(它没有 getList 方法)。

(稍微随意使用缩进和换行来说明问题):

[       '$scope','modFact','quizIndexFactory', '$http',
function($scope, $http, quizIndexFactory, modFact) {
    ...
}]

应该是:

[       '$scope', '$http', 'quizIndexFactory', 'modFact',
function($scope, $http, quizIndexFactory, modFact) {
    ...
}]

关于javascript - Angular 工厂函数抛出错误声称它不是 Controller 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36169354/

相关文章:

javascript - Firefox 扩展在文档中显示图像

javascript - jquery 单击 div 上的绑定(bind),影响驻留在其中的文本框

javascript - 我在测试 Angular 1.5 组件时遇到问题

javascript - 更改 axios header 中的 Content-Type 以修复 415 错误

javascript - 使用 fetch 的基本身份验证(或任何身份验证)

rest - 模拟HTTP上的过程调用的最佳/最RESTful方法是什么?

javascript - 未捕获的类型错误 : Cannot use 'in' operator to search for 'scrollLeft' in undefined

javascript - Safari WebDriver setTimeout 使用 Protractor 退出

python - 使用 angularjs 和 flask 进行用户身份验证的正确方法

javascript - 尝试在服务文件中使用 ng-model