最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Provider 'xx' must return a value from $get factory method - Stack Overflow

programmeradmin2浏览0评论

Here is my angular service:

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

I think this service is returning data (or an empty array // not sure)

Then why am I geeting this error:

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

Update:

If I use service instead of factory then I don't get any errors. Why so???

Here is my angular service:

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

I think this service is returning data (or an empty array // not sure)

Then why am I geeting this error:

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

Update:

If I use service instead of factory then I don't get any errors. Why so???

Share Improve this question edited Aug 10, 2016 at 22:20 Vishal asked Aug 10, 2016 at 22:15 VishalVishal 6,37814 gold badges89 silver badges164 bronze badges 1
  • 2 Answering the update: factory() and service() return different values by design. From tylermcginnis./angularjs-factory-vs-service-vs-provider I found this: When you’re using a Factory you create an object, add properties to it, then return that same object. When you’re using Service, it’s instantiated with the ‘new’ keyword. Because of that, you’ll add properties to ‘this’ and the service will return ‘this’. I don't have an explanation; this is just the nature of the beast. – msenne Commented Mar 13, 2018 at 19:00
Add a ment  | 

2 Answers 2

Reset to default 6
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,
  }


});

The error speaks for itself. You must return something in your factory:

var factory = {
  fetch: fetch
};

return factory;

function fetch() {
  return..
}

Then, in your controller:

partyService.fetch()...
发布评论

评论列表(0)

  1. 暂无评论