0

我写了一个服务,依赖于其他服务。但是初始化不起作用。

你可以找到一个 plunker 作为展示

应该快上班了……有什么小费吗?提前致谢!

编辑:plunker 现在已修复,可用作参考。

4

2 回答 2

1

您需要将您的testServiceMockConfigand testServicefrom更改factoryservice,例如:

.service('testServiceMockConfig', function ()

或将它们保留为工厂并添加return.this;到它们的底部或像这样重组它们(推荐):

angular.module('testServiceMockConfig', [])
  .factory('testServiceMockConfig', function() {
    console.log("setup cqrs mock config.");

    return {
      doLoadItems: function(callback) {
        console.log("mock loading data");
        if (!this.configuredLoadItems) {
          throw Error("The mock is not configured to loadItems().");
        }
        callback(this.loadItemsError, this.loadItemsSuccess);
      },
      whenLoadItems: function(success, error) {
        this.configuredLoadItems = true;
        this.loadItemsSuccess = success;
        this.loadItemsError = error;
      }
    };
  });

我还假设loadItemsintestService应该调用:

testServiceMockConfig.doLoadItems(callback);

代替:

testService.doLoadItems(callback);
于 2013-11-06T20:58:02.823 回答
1

正如我从你的例子中看到的,

  • 你没有正确定义factory.The thiskey used forservice
  • testService.doLoadItems(callback);代替_ testServiceMockConfig.doLoadItems(callback);

您可以在这个简单的演示中找到服务-工厂-提供者和定义之间的区别:

Fiddle

固定示例:

angular.module('testServiceMockConfig', [])
    .factory('testServiceMockConfig', function () {
        console.log("setup cqrs mock config.");

        return{
        doLoadItems : function (callback) {
            console.log("mock loading data");
            if (!this.configuredLoadItems) {
                throw Error("The mock is not configured to loadItems().");
            }
            callback(this.loadItemsError, this.loadItemsSuccess);
        },
        whenLoadItems : function (success, error) {
            this.configuredLoadItems = true;
            this.loadItemsSuccess = success;
            this.loadItemsError = error;
        }
        }
    });


angular.module('testService', ['testServiceMockConfig'])
    .factory('testService', ['testServiceMockConfig', function (testServiceMockConfig) {

        console.log("mock version. testServiceMockConfig: ");

        return {
          loadItems : function (callback) {
            testServiceMockConfig.doLoadItems(callback);
        }
        }
    }])


angular.module('ItemApp', ['testService'])
    .controller('ItemsCtrl', ['$scope', 'testService', function ($scope, testService) {
        $scope.text = 'No items loaded';
        testService.loadItems(function (error, items) {
            if (error) {
                $scope.text = "Error happened";
            }
            $scope.text = '';
            for (i = 0; i < items.length; i++) {
                $scope.text = $scope.text + items[i].name;
            }
        })
    }]);

演示Plunker

于 2013-11-06T21:00:05.387 回答