调用工厂方法时出现 Angularjs 错误

Angularjs error when calling factory method

本文关键字:Angularjs 错误 工厂 方法 调用      更新时间:2023-09-26

我是 angularjs 的新手。我正在尝试在工厂中调用函数,但出现以下错误,

Error: [$injector:undef] Provider 'todoStorage' must return a value from $get factory method.

这是我的工厂,

todomvc.factory('todoStorage', function ($q,$http) {
var STORAGE_ID = 'todos-angularjs-perf';
 function get(){
            var promise = $q.defer();
            $http.get('http://localhost/test.php').success(function(data){
                    promise.resolve(data);
            });
            return promise.promise;
        }
});

这就是我调用函数的方式,

var todos = $scope.todos = todoStorage.get();

究竟发生了什么,为什么会出现此错误?

todomvc.factory('todoStorage', function ($q,$http) {
var STORAGE_ID = 'todos-angularjs-perf';

 function get(){
   return $http.get('http://localhost/test.php');
 }
 return{get:get};
});
//call the service like this
todoStorage.get().then(function(res){
  $scope.todos = res.data;
});

代码未返回实际的服务工厂。由于您使用的是工厂,因此您返回了一些指向内部函数的JavaScript对象。否则,它不是一个有效的工厂,并且您的外部代码将无法访问内部 get 函数。