在我的SchoolyearController中,参数schoolyears是未定义的。
如何在schoolyearService中检索我的schoolyears对象并将结果注入SchoolyearController?
服务
'use strict';
angular.module('schoolyear').service('schoolyearService', function ($http) {
return {
getSchoolyears: function () {
var path = 'scripts/model/schoolyears.json';
$http.get(path).then(function (response) {
return response.data.schoolyears; // The schoolyears here are the 6 expected JS objects in an array, so far so good but how do I get those objects into the SchoolyearController as parameter ?
});
}
};
});
UI-ROUTER
resolve: {
schoolyearService: ['schoolyearService',
function (schoolyearService) {
return schoolyearService.getSchoolyears();
}]
},
CONTROLLER
'use strict';
angular.module('schoolyear').controller('SchoolyearController', function ($scope, schoolyears) {
$scope.schoolyears = schoolyears; // I do not want to do a $http request here I just want to get passed the data here !!!
});
更新
解决后的属性中的校园仍然未定义,为什么?
FACTORY
'use strict';
angular.module('schoolyearModule').factory('schoolyearFactory', function ($http) {
return {
getSchoolyears: function () {
var path = 'scripts/model/schoolyears.json';
$http.get(path).then(function (response) {
return response.data.schoolyears; // The schoolyears here are the 6 expected JS objects in an array
});
}
};
});
UI-ROUTER
resolve: {
schoolyears: function(schoolyearFactory) {
var schoolyears = schoolyearFactory.getSchoolyears();
return schoolyears;
}
},
CONTROLLER
'use strict';
angular.module('schoolyearModule').controller('ProjectsController', function ($scope, schoolyears) {
$scope.schoolyears = schoolyears; // I do not want to do a $http request here I just want to get passed the data here !!!
});
答案 0 :(得分:2)
您的已解析值名为schoolyearService
(因此与具有相同名称的服务发生冲突):
resolve: {
schoolyearService: ...
但您尝试使用名称schoolyears
注入它:
angular.module('schoolyear').controller('SchoolyearController',
function ($scope, schoolyears) {
在任何地方使用相同的名称(schoolyears
):
resolve: {
schoolyears: ...
此外,您应该使用factory()方法来定义服务,而不是servoce()方法。 service()
方法将构造函数作为参数,而不是将对象作为实际服务实例返回的函数。
编辑:
此外,您没有从getSchoolyears()
服务方法返回任何内容。因此返回undefined
。你需要的是:
getSchoolyears: function () {
var path = 'scripts/model/schoolyears.json';
return $http.get(path).then(function (response) {
return response.data.schoolyears;
});
}