범위 어레이 변수는 항상 0을 보여줍니다. 그러나 JSON은 각도의 데이터를 표시합니다.
-
21-12-2019 - |
문제
Angularjs 및 Spring Rest Service를 사용하고 있습니다.매우 간단한 시나리오는 아니지만 문제가 무엇인지 알지 못합니다!
이것은 Service.js에서 정의 된 Daya의 배열을 반환하는 내용 컨트롤러입니다.아래 코드에서 콘솔은 항상 0을 반환합니다.
Controller.js
$scope.allreviews = PostFactory.reviews.query({key: reviewId});
console.log('read more' + $scope.allreviews.length);
.
서비스 .js
reviews: $resource('/ngdemo/web/posts/review/:key', {}, {
query: {method: 'GET', isArray: true, params: {key: '@key'} },
create: {method: 'POST'}
})
.
이제 리뷰 메소드에 정의 된 REST 서비스는 Firefox 콘솔 GET 메소드에서 볼 수있는 데이터를 반환합니다.그러나 그것은 도달 컨트롤러도이므로 데이터에 액세스 할 수 없습니다.문제가 무엇인지 제안 할 수 있습니까?
iSerray 제거 시도 : true 그러나 오류 $ destination.push는 NT입니다.
제안
를 제안하십시오해결책
당신이 직면하고있는 문제는 $resource
의 비동기적 성질과 관련이 있습니다.스코프의 일부 속성에 자원 쿼리를 할당 할 때마다 실제로 관련된 응답이 올 때까지 채워진 빈 객체의 종류를 실제로 할당합니다.따라서 동기식 방식으로 직접 데이터에 액세스 할 수 없습니다.일단 데이터에 액세스 할 수있는 몇 가지 다른 방법이 있습니다.다음은 두 가지 가능한 방법이 있습니다 (콜백 함수를 쿼리 및 $scope.$watch()
의 인수로 사용) :
자바 스크립트
angular.module('app',['ngResource']).
controller('PostController',['$scope', 'PostFactory', function($scope, PostFactory) {
var reviewId = 'post.json';
$scope.allreviews = PostFactory.reviews.query({key: reviewId}, function(allreviews) {
console.log('(callback) read more ' + $scope.allreviews.length); // <= will log correct length
});
console.log('read more ' + $scope.allreviews.length); // <= will always log 0
$scope.$watch('allreviews.length', function(length) {
if(length) { // <= first time length is changed from undefined to 0
console.log('(watch) read more ' + $scope.allreviews.length); // <= will log correct length
}
});
}]).
factory('PostFactory', ['$resource', function($resource) {
return {
reviews: $resource(':key', {}, {
query: {method: 'GET', isArray: true, params: {key: '@key'} },
create: {method: 'POST'}
})
}
}]);
.
plunker : http://plnkr.co/edit/vy52x0ljkgsl4nesenuy?p=preview
다른 팁
결과를 로그 아웃하기 전에 쿼리가 완료 될 때까지 기다려야합니다. 각도 문서 :
$ 자원 객체 메소드를 호출하는 것이 중요합니다. 즉시 빈 참조 (객체 또는 배열에 따라 다름)를 반환합니다. Isarray).데이터가 서버에서 리턴되면 참조는 실제 데이터로 채워집니다.
이렇게 할 수 있습니다
$scope.allreviews = PostFactory.reviews.query({key: reviewId} function() {
console.log('read more' + $scope.allreviews.length);
});
.