TypeError: api.getAll is not a function, service method is not recognized

大憨熊 提交于 2019-12-11 00:31:55

问题


I have a very simple service and a controller attempting to get some information from it, but I keep getting .methodName is not a function.

Here is the service, apiService.js :

(function (module) {

    function api() {

        var sharedService = {};

        sharedService = {

            getAll: function () {
                return 'test';
            }
        };
        return sharedService;

    }

    module.factory("api", api);


}(angular.module("anbud")));

Then I attempt to use my method getAll in the controller, like this:

(function () {
    'use strict';

    angular.module('anbud')
      .controller('BasicExampleCtrl', ['$scope', 'api', function (api, $scope) {

           // on successfull request
          function onJson(json) {
              $scope.data = json;
          }

          // error getting json
          function onError() {
              throw 'error getting json';
          }

          function initialize() {

              api.getAll()
                  .then(onJson, onError);
          }

          initialize();

      }]);

}());

But I get the error:

TypeError: api.getAll is not a function
    at initialize (basic-example.js:67)

Any help is appreciated thank you.


回答1:


You have interchanged the dependencies sequence inside controller factory function, the sequence must be same as they are included in DI array while injecting in function.

Code

.controller('BasicExampleCtrl', ['$scope', 'api', function ($scope, api) { //<- first $scope then api.



回答2:


try it like this:

.controller('BasicExampleCtrl', ['$scope', 'api', function ($scope,api) {


来源:https://stackoverflow.com/questions/33673051/typeerror-api-getall-is-not-a-function-service-method-is-not-recognized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!