2013-12-09 70 views
4

我有一個REST API,它返回User對象,其中的角色是通過指向另一個對象的鏈接指定的。因此,在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是未定義的。我還嘗試將transformResponse param添加到用戶服務GET操作中,但該功能從未被調用過。

第二個選項工作得很好 - 除了我必須硬編碼用戶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關鍵。