它已经像6-7个月的角度,我已经获得了不是很多,但相关的知识。但从过去的一天起,我就被这个错误困住了,如下所示:
错误:$injector:undef$注入器/undef?p0=DataService 堆栈跟踪: K/<@http://localhost:64965/Scripts/angular.min.js:7:76
以下是我的服务代码:
(function () {
var DataService = function ($http) {
var allItems = function () {
return $http.get("./data/myData.json").then(function (serviceResp) {
return serviceResp.data;
});
};
};
app.factory("DataService", ["$http", DataService]);
}());以下是我的控制器代码:
(function () {
var ItemController = function ($scope, DataService) {
var allItems = function (data) {
$scope.collection = data;
};
};
app.controller("ItemController", ["$scope", "DataService", ItemController])
}());工厂正在返回对象,但我还是得到了上面的错误。我多次尝试清理缓存,并多次重新启动该应用程序。
发布于 2017-08-30 05:06:21
你写服务的方式是错误的。
它应以下列方式写成:
var app = angular.module('ServiceExample',[]);
var serviceExampleController =
app.controller('ServiceExampleController', ServiceExampleController);
var serviceExample = app.service('NameOfTheService', NameOfTheService);
ServiceExampleController.$inject = ['NameOfTheService'] //protects from minification of js files
function ServiceExampleController(NameOfTheService){
serviceExampleController = this;
serviceExampleController.data = NameOfTheService.getSomeData();
}
function NameOfTheService(){
nameOfTheService = this;
nameOfTheService.data = "Some Data";
nameOfTheService.getSomeData = function(){
return nameOfTheService.data;
}
}然后,在HTML中,您可以像这样使用它:
<div ng-controller = "ServiceExampleController as serviceExample">
{{serviceExample.data}}
</div>如果您想使用factory,请阅读this post。
发布于 2017-08-30 06:39:40
工厂必须返回值/obj。你什么都没还给我。我还没有测试过,但它应该能用。
(function () {
var DataService = function ($http) {
var allItems = function () {
return $http.get("./data/myData.json").then(function (serviceResp) {
return serviceResp.data;
});
};
return allItems ;
};
app.factory("DataService", ["$http", DataService]);
}());https://stackoverflow.com/questions/45952164
复制相似问题