提供者'xx'必须从$ get factory方法返回一个值

Vis*_*hal 8 javascript angularjs

这是我的角度服务:

angular
    .module('myApp')
    .factory('partyService', function($http) {
        this.fetch = function() {
            return $http.get('/api/parties')
                        .then(function(response) {
                            return response.data;
                        });
        }
    });
Run Code Online (Sandbox Code Playgroud)

我认为这个服务正在返回数据(或者是一个空数组//不确定)

那我为什么要纠结这个错误:

错误:[$ injector:undef]提供者'partyService'必须从$ get factory方法返回一个值.

更新:

如果我使用服务而不是工厂,那么我不会有任何错误.为什么这样???

dev*_*033 5

这个错误不言而喻.你必须在工厂归还一些东西:

var factory = {
  fetch: fetch
};

return factory;

function fetch() {
  return..
}
Run Code Online (Sandbox Code Playgroud)

然后,在你的controller:

partyService.fetch()...
Run Code Online (Sandbox Code Playgroud)

  • 是的,这非常有效.谢谢.我从来不知道我的工厂没有退货.我只觉得我在工厂里面有两个return语句,所以我将返回数据. (2认同)

D V*_*esh 5

angular
.module('myApp')
.factory('partyService', function($http) {

    function fetch = function() {
        return $http.get('/api/parties')
                    .then(function(response) {
                        return response.data;
                    });
    }

    function anotherFetch = function() {
        return $http.get('/api/parties')
                 .then(function(response) {
                     return response.data;
                 });
    }

  return {
    fetch,
    anotherFetch,
  }


});
Run Code Online (Sandbox Code Playgroud)