【问题标题】:Links (relations) to REST resources in AngularJSAngularJS 中到 REST 资源的链接(关系)
【发布时间】:2013-12-26 22:17:36
【问题描述】:

我有一个 REST API,它返回用户对象,它的角色是通过链接到另一个对象来指定的。所以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,我不知道如何。

感谢您的任何建议。

【问题讨论】:

    标签: javascript rest angularjs hypermedia ngresource


    【解决方案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 告诉 Angular 使用传递的参数中的 id 键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-04
      • 2019-01-24
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      • 2014-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多