TypeError: api.getAll is not a function, service m

2019-07-18 23:05发布

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.

2条回答
We Are One
2楼-- · 2019-07-18 23:50

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.
查看更多
我想做一个坏孩纸
3楼-- · 2019-07-19 00:07

try it like this:

.controller('BasicExampleCtrl', ['$scope', 'api', function ($scope,api) {
查看更多
登录 后发表回答