将 $resource 与休息服务一起使用

Using $resource with rest service

我正在尝试熟悉 $resource 以便使用 RESTful Web 服务。

因此,为了尝试,我声明了一个这样的工厂:

'use strict';

angular.module('BalrogApp').factory('Req', ['$resource', function($resource) {
  return $resource('http://localhost:8000/api/catalog/requests/:id', {id: '@id'}, {
    'update': { method: 'PUT'},
    'query': { method: 'GET'}
  });
}]);

在我的控制器中我有这个:

angular.module('BalrogApp').controller('requestsController', function(Req, $route, $rootScope, $scope, $location, $routeParams) {
  this.$route = $route;
  var controllerScope = this;

  this.r = Req.get({ id:4 });

  console.log(this.r);

这很好用,在我的控制台中,我可以看到我的对象以及从服务中检索到的 id 为 4 的项目的数据。

但是我不确定我是否正确检索了数据,因为我存储在 r 中的对象在对象详细信息中包含一个 id(单击 "Object"浏览器控制台显示对象详细信息,包括其 ID),但控制台上显示的对象本身 (r) 仅包含 2 个字段,显示如下:Object { $promise: Object, $resolved: false }.

所以,最后,console.log(this.r); 有效,但 console.log(this.r.id); 无效,即使 r 应该包含一个 id,就像在浏览器检查器的对象详细信息中一样。

此外,我如何配置此服务才能像我正在做的那样将 get()id 参数一起使用,这会导致调用 http://localhost:8000/api/catalog/requests/:id 但也会没有导致调用 http://localhost:8000/api/catalog/requests

id 参数

由于对 REST API 的调用是异步的,您在使用 Req.get({ id:4 });

时大喊等待返回的承诺解决

使用:

Req.get({ id:4 }).$promise.then(function(result){
  console.log(JSON.stringify(result));
});

相反。

对于问题的第二部分:使用没有 id 属性 的数据应该没问题。但是,此数据将在请求正文中传输,而不是作为请求参数。