2013-12-09 6 views
4

REST API가 있는데,이 객체는 다른 객체에 대한 링크를 통해 역할이 지정되는 사용자 객체를 반환합니다. 따라서 localhost/project/api/users/27/은 JSON 객체입니다.AngularJS의 REST 리소스에 대한 링크 (관계)

{ 
    "id": 42, 
    "name": "John", 
    "prijmeni": "Doe", 
    "login": "johndoe", 
    "nickname": null, 
    "grade": 1.3, 
    "roles": { 
     "href": "http://localhost/project/api/users/1716/roles/" 
    } 
} 

내가하려는 것은 컨트롤러에서 역할을 얻는 것입니다. 내 사용자 서비스는 다음과 같습니다

projectServices.factory('User', ['$resource', 'UserRoles', 
    function($resource, UserRoles, Role) { 
     var User = $resource('http://localhost/project/api/users/:id', {}, { 
      'query': { 
       method: 'GET', 
       isArray: true 
      } 
     }); 
     return User; 
    } 
]); 

나는 (그 자원 코드 블록에) 추가하려고 : ngRepeat에 전화했을 때

User.prototype.roles= function(){ 
    return UserRoles.get({id:42}); 
}; 

이 하나의 브라우저를 정지. 그래서 시도했습니다

User.prototype.roles = UserRoles.get({id:42}); 

이 작동합니다. 시도한 후

User.prototype.roles = $resource(this.roles.href, {}, { 
    'get': { 
     method: 'GET', 
     isArray: true 
    } 
}); 

에 의하면 roles은 정의되지 않았습니다. 또한 사용자 서비스 GET 작업에 transformResponse 매개 변수를 추가하려고 시도했지만 해당 함수가 호출되지 않았습니다.

두 번째 옵션은 사용자 ID를 하드 코드해야한다는 것을 제외하고는 완전히 완벽하게 작동합니다. 적절한 솔루션은 어떻게 든 나를 위해 사용자 ID를 얻는 것입니다 (나는 시도했습니다 this.id,하지만 그 작동하지 않았다).

완벽한 솔루션은 주어진 href에서 리소스를 생성하지만, 프로토 타입에서는 roles에 액세스 할 수 없으므로 어떻게해야할지 모릅니다.

어떤 조언을 주셔서 감사합니다.

답변

1

이 트릭을 할해야

projectServices.factory('UserRoles', function(){ 
    return $resource('http://localhost/project/api/users/:id', {id: @id}, 
     {'query': { 
      method: 'GET', 
      isArray: true 
     }) 
} 

이제

UserRoles.get({id:42}) 
// this makes the request :  http://localhost/project/api/users/42 

로 호출 할 수는이 전달 된 매개 변수에서 ID 키를 사용하여 각도 알려줍니다 @id.