0
저는 Service
과 Controller
입니다. 컨트롤러는 Service
에있는 getItems()
함수를 호출합니다. Service
은 array
개의 데이터를 반환합니다.컨트롤러가 서비스 데이터를 가져 오지 않습니다.
그러나 컨트롤러가 이상한 메시지를받지 못하는 것으로 보입니다.
컨트롤러 :
ItemModule.controller('ItemController', ['$scope', 'ItemService',
function ($scope, ItemService) {
$scope.items = [];
$scope.getItems = function() {
$scope.items = ItemService.getItems();
}
$scope.getItems();
}
]);
서비스 : 내가 잘못
ItemModule.service('ItemService', ['$rootScope', '$http',
function($rootScope, $http) {
this.getItems = function() {
$http.get($rootScope.root + '/products').success(function(data) {
// This prints it out fine to the console
console.log(data);
return data;
});
}
}
]);
을 뭐하는 거지? 컨트롤러가 경로의 일부인 경우 (아마도
ItemService.getItems($scope);
그러나 :
ItemModule.service('ItemService', ['$rootScope', '$http',
function($rootScope, $http) {
return {
getItems : function(scope) {
$http.get($rootScope.root + '/products').success(function(data) {
scope.items = data;
});
}
}
}
]);
다음 컨트롤러에 바로 전화 :
'$ http.get'은 비동기식이고'success'는 콜백입니다. 그것으로부터 돌아 오는 것은 잘못입니다 (당신이 기대하는 것을하지 않습니다). 이것을 읽으십시오 : http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call#answer-14220323 –
문제는 HTTP 약속을 돌려줌으로써 해결 될 것입니다. 'return $ http.get (... 기존 코드를 변경하지 않고 ...)' –
또한 서비스에서 작성한 객체를 반환하지 않으므로'ItemService.getItems();를 호출하면 메소드가 오류라는 것을 알 수 있습니다. 정의되지 않은 – charlietfl