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

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

我有一个非常简单的服务和一个试图从中获取一些信息的控制器,但我一直收到 .methodName 不是函数。

这是服务,apiService.js

(function (module) {

    function api() {

        var sharedService = {};

        sharedService = {

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

    }

    module.factory("api", api);


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

然后我尝试在控制器中使用我的方法 getAll,如下所示:

(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();

      }]);

}());

但我收到错误消息:

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

感谢任何帮助,谢谢。

您在 controller 工厂函数中交换了依赖序列,注入函数时序列必须与 DI array 中包含的序列相同。

代码

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

试试这样:

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