我写了一个服务,依赖于其他服务。但是初始化不起作用。
应该快上班了……有什么小费吗?提前致谢!
编辑:plunker 现在已修复,可用作参考。
您需要将您的testServiceMockConfig
and testService
from更改factory
为service
,例如:
.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;
}
};
});
我还假设loadItems
intestService
应该调用:
testServiceMockConfig.doLoadItems(callback);
代替:
testService.doLoadItems(callback);
正如我从你的例子中看到的,
factory.
The this
key used forservice
testService.doLoadItems(callback);
代替_ testServiceMockConfig.doLoadItems(callback);
您可以在这个简单的演示中找到服务-工厂-提供者和定义之间的区别:
固定示例:
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