Javascript AngularJS资源工厂始终返回空响应

Javascript AngularJS资源工厂始终返回空响应,javascript,jquery,angularjs,angularjs-resource,Javascript,Jquery,Angularjs,Angularjs Resource,好吧,我想我在这里遗漏了一些基本的东西,但在阅读文档和其他示例时我无法理解。我在工厂里有这样的资源: loteManager.factory('Lotes', function($resource) { return $resource('./api/lotes/:id',{ id:"@id" }, { get: {method:'GET', isArray:true} }); }); loteManager.controller('LoteCtrl', functi

好吧,我想我在这里遗漏了一些基本的东西,但在阅读文档和其他示例时我无法理解。我在工厂里有这样的资源:

loteManager.factory('Lotes', function($resource) {
  return $resource('./api/lotes/:id',{ id:"@id" }, {
     get:  {method:'GET', isArray:true}
   });
});
loteManager.controller('LoteCtrl',
  function InfoCtrl($scope, $routeParams, Lotes) {
    Lotes.get({id: $routeParams.loteId}, function (response){
      console.log(response);
    });
});
$routeProvider.when('/somepath/:loteId, {
    templateUrl: 'sometemplate.html',
    controller: LoteCtrl
});
和我的控制器:

loteManager.controller('LoteCtrl',
  function InfoCtrl($scope, $routeParams, Lotes) {
    Lotes.get(function (response){
      console.log(response);
    });
});

当我像这样手动定义id时,它可以工作。
$resource('./api/lotes/21'
,因此我认为问题在于将id传递给工厂,但我已经尝试添加
参数:{id:@id}
,但这也不起作用。

您需要传递id

大概是这样的:

loteManager.factory('Lotes', function($resource) {
  return $resource('./api/lotes/:id',{ id:"@id" }, {
     get:  {method:'GET', isArray:true}
   });
});
loteManager.controller('LoteCtrl',
  function InfoCtrl($scope, $routeParams, Lotes) {
    Lotes.get({id: $routeParams.loteId}, function (response){
      console.log(response);
    });
});
$routeProvider.when('/somepath/:loteId, {
    templateUrl: 'sometemplate.html',
    controller: LoteCtrl
});
…假设您定义了一条如下所示的路线:

loteManager.factory('Lotes', function($resource) {
  return $resource('./api/lotes/:id',{ id:"@id" }, {
     get:  {method:'GET', isArray:true}
   });
});
loteManager.controller('LoteCtrl',
  function InfoCtrl($scope, $routeParams, Lotes) {
    Lotes.get({id: $routeParams.loteId}, function (response){
      console.log(response);
    });
});
$routeProvider.when('/somepath/:loteId, {
    templateUrl: 'sometemplate.html',
    controller: LoteCtrl
});
根据:


我想你的问题是你说你的'get'方法(id)有参数,但是你在Lotes.get(…)上调用时没有给'get'方法一个id

因此,我认为,您的方法调用应该是

Lotes.get({id: SOME_Id}, function(response){
    // ...do stuff with response
});
我不完全确定这种语法,因为我个人更喜欢服务,因为它提供了更大的灵活性,但这就是您的代码的问题所在。一般来说,您没有为您的方法提供所需的参数(id)


另外,在进行异步调用时,请记住使用Angular的服务。

ahh刚刚看到@moderndegree的帖子。因此,我想我的语法是正确的,但仍请记住$timeout服务,您将在一秒钟内需要它。您能详细说明为什么我必须使用$timeout服务吗?如果没有它,它现在似乎可以正常工作。所以$resource正在发出异步请求。由于Javascript天生是同步的,因此需要$timeout系统(在一定的毫秒数内)才能完成异步请求。