2016-07-18 4 views
2

서버에 편안한 요청을하기 위해 $resource을 사용하고 있습니다. 내 코드가개체의 속성에 액세스 할 수 없습니다.

service.js

.factory('userServ',function($resource){ 
    return $resource('url/:id',{id:'@id'},{ 
      me: 'GET',isArray:false,url:'url2'} 
}); 
}) 

나는이

$scope.userDetails = userService.me(); 
console.log($scope.userDetails) // gives all the details of the user 
console.log($scope.userDetails.username) // gives undefined. But username is there in the object 

같은 컨트롤러에이 서비스를 사용하고 그래서 어떻게 액세스 할 수있는 객체

+1

서비스 메소드 호출에'.then' 콜백을 넣어야합니다. 콜백 내에 성공과 오류 콜백이 있습니다. –

+1

@PankajParkar 왜 대답을 게시하지 않으시겠습니까? – dfsq

답변

0

에서 그 너의 aprroach, 약속은 해결되지 않습니다. 따라서 데이터에 액세스 할 수 없습니다. 여기 ,

$scope.userDetails = userService.me(); 


약속가 해결되지 않습니다. Object를 확장하면 resolved:false이 표시됩니다. $scope.userDetails 안에 데이터를 볼 수는 있지만 필요한 것은 있습니다.

그래서 약속이 해결 될 때까지 기다려야합니다.이 경우 .then 방법을 사용할 수 있습니다.

var CallApi = userService.me().$promise; //Promise yet to be Resolved 
     CallApi.then(function (res)){   //Promise resolved here 
     $scope.userDetails = res; 
     console.log($scope.userDetails) 
     console.log($scope.userDetails.username) 
     } 
    }) 
+1

자세한 내용을 편집하십시오. 코드 전용 및 "시도하십시오"답변은 검색 가능한 콘텐츠가 없으므로 권장하지 않으며 누군가가 "시도해"야하는 이유를 설명하지 않습니다. – abarisone

+0

@ bararisone 귀하의 제안을 따를 것입니다. – Ved

0

리소스 개체가 약속을 반환합니다. 여기에 대한 자세한 내용을 읽어 그것의 데이터를 얻기 위하여 https://docs.angularjs.org/api/ngResource/service/$resource

var myResource = $resource('url/:id',{id:'@id'},{ 
     me: 'GET',isArray:false,url:'url2'} 
}); 

당신이 약속 자체의 메소드를 호출 할 필요가있다. 그들은 GET, PUT 및 SAVE입니다.

하지만 여기에는 GET이 언급되어 있습니다.

그럼 당신은 반환 된 데이터를해야합니다 여기, 지금 'myResult을'

var myResult = []; 
myResource.then(function(data){ 
    myresult = date; 
}); 

를 호출하여 약속을 해결합니다.

은 또한이()처럼 호출 할 수 있습니다

.get({userId:123}) 
.$promise.then(function(user) { 
    $scope.user = user; 
}); 

는 다시 나는 더 나은 이해를 얻기 위해 각 문서를 읽고 추천 할 것입니다.

관련 문제