我尝试在factory
内访问controller
服务以获取正确的数据。
相关的控制器代码如下:
myApp.controller('RegistrationController', ['$scope','$routeParams','$rootScope','$location','$filter','$mdDialog','checkAttendee', function($scope, $routeParams, $rootScope, $location, $filter, $mdDialog,checkAttendee){
...
$scope.addAttendee = function(ev) {
$mdDialog.show({
controller: AddDialogCntrl,
templateUrl: 'views/regForm.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true,
controllerAs: 'ctrl',
fullscreen: $scope.customFullscreen, // Only for -xs, -sm breakpoints.
locals: {parent: $scope}
})
.then(
function(response){
if(angular.isDefined(response)){
attendees.push(response);
checkAttendee.getAttendeeInfo(response);
}
},
function(){
//no changes
}
)
.catch(
function(error) {
console.log('Error: ' + error);
}
)
};
和factory
服务代码
myApp.factory('checkAttendee', ['$http', function($http) {
this.getAttendeeInfo = function(req) {
return $http.get("/check/attendee/", {params:{"firstName":req.firstName, "lastName":req.lastName, "email": req.email, "eventID": req.eventID}})
.then(function(response) {
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
console.log('Data: ' + data);
console.log('Status: ' + status);
return data;
})
.catch(function(response) {
console.log('something worng');
});
}
}]);
但是当有返回值时,该组合会给我一个错误Provider 'checkAttendee' must return a value from $get factory method.
。
有什么想法吗?
答案 0 :(得分:2)
当我们与工厂合作时,结构应该是:
myApp.factory('checkAttendee', ['$http', function($http) {
var factory = {
getAttendeeInfo : function () {
return $http.get(/**/).then(function(response) {
// ..
return data;
}
}
}
return factory;
}]);
您可以将factory
更改为service
,一切都应该有效。 A.e:
myApp.service('checkAttendee', ['$http', function($http) {
this.getAttendeeInfo = function(req) {
return $http.get("/check/attendee/", {params:{"firstName":req.firstName, "lastName":req.lastName, "email": req.email, "eventID": req.eventID}})
.then(function(response) {
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
console.log('Data: ' + data);
console.log('Status: ' + status);
return data;
})
.catch(function(response) {
console.log('something worng');
throw response;
});
}
}]);
请注意service
扩展了factory