AngularJS中REST资源的链接(关系)

Links (relations) to REST resources in AngularJS

本文关键字:关系 链接 REST 资源 AngularJS      更新时间:2024-06-08

我有一个REST API,它返回User对象,其中它的角色通过链接到另一个对象来指定。所以在localhost/project/api/users/27/是JSON对象:

{
    "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;
    }
]);

我试图添加(到资源代码块):

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

这个在ngRepeat中调用时会冻结浏览器。所以我尝试了

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

这是有效的。然后我尝试了

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

roles是未定义的。我还尝试将transformResponse参数添加到用户服务GET操作中,但该函数从未被调用。

第二个选项运行得很好,只是我必须对用户ID进行硬编码。合适的解决方案是以某种方式为我获取用户ID(我尝试了this.id,但没有成功)。

完美的解决方案是从给定的href创建资源,但由于我无法访问原型中的roles,我不知道如何访问。

谢谢你的建议。

这应该可以完成

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告诉angular使用传递参数中的id