AngularJS 컨트롤러에서 JSONP 요청을 만드는 함수를 만들었습니다. 이 요청은 다음 형식을 가진 JSONP 객체를 반환합니다.
[{
"Domain_1":{
"Notes":"This information can be usefull for generic information",
"Contacts":[
{
"ContactName":"P. rimary",
"ContactPhone":"+31 612 273 88"
}
]
},
"Domain_2":{
"Notes":"This information can be usefull for generic information",
"Contacts":[
{
"ContactName":"S. secondary",
"ContactPhone":"+31 612 273 88"
}
]
}
}];
다음 함수에서 JSONP 요청을 할 때 객체가 성공적으로 반환됩니다. ($ scope.method 및 $ scope.domainName은 범위 수준에서 설정 됨) 내가 원하는 것은 $ scope.domainName의 값과 일치하는 JSON 데이터의 특정 부분을 선택하고이를 범위 변수 $ scope에 할당하는 것입니다. domainData.
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
// Only make JSONP request if domain name is known
if ($scope.domainName !== null) {
$http({method: $scope.method, url: $scope.url, timeout: 5000}).
success(function(data, status) {
$scope.status = status;
console.log("Data:") ; console.dir(data) ;
console.log("Domain Name" + $scope.domainName) ;
$scope.domainData = data[$scope.domainName] ;
console.log("DomainData: ") ;
console.dir($scope.domainData) ;
}).
error(function(data, status, headers, config) {
$scope.domainData = null ;
$scope.status = status;
console.log("$scope.fetch failed" + $scope.status + " :: " + data) ;
});
} else {
console.log("Shame... nothing to do..... ") ;
}
};
코드가 실행되면 도메인 이름은 "Domain_1"이고 데이터에는 다음이 포함됩니다 (콘솔에 표시됨).
0: Object
Domain_1: Object
Contacts: Array[1]
0: Object
ContactName:"P. rimary"
ContactPhone:"+31 612 273 88"
...
그러나 $ scope.domainData는 정의되지 않았습니다. 이 선택이 올바르게 작동하도록하려면 어떻게해야합니까?
응답 개체는 캡슐화 대괄호를 기반으로 최상위 수준의 배열로 나타납니다. 즉, 도메인 이름으로 직접 역 참조 할 수 없습니다. 이를 해결하기위한 한 가지 접근 방식은 성공 기능에서 다음과 같은 것입니다.
$scope.domainData = data[0][$scope.domainName];
이것은 물론 0
응답 객체가 길이 1의 배열이 될 것이라고 항상 확신 하는 경우 에만 하드 코딩하는 것이 좋습니다 (예제에서와 같이). 항상 그런 것이 아니라면 일치하는 속성을 찾는 일종의 반복 순회를 구현해야 할 수 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다