AngularJS资源工厂总是返回空响应

AngularJS resource factory always returns empty response

本文关键字:返回 响应 资源 工厂 AngularJS      更新时间:2023-09-26

好的,所以我认为我在这里缺少了一些基本的东西,但我在阅读文档和其他示例时无法理解。我在这样的工厂里有一个资源:

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(function (response){
      console.log(response);
    });
});

当我像$resource('./api/lotes/21'这样手动定义id时,它就起作用了,所以我认为问题是将id传递给工厂,但我已经尝试添加params:{id:"@id"},但也不起作用。

您需要传入id。

类似这样的东西:

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
});

根据文件:

var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
  user.abc = true;
  user.$save();
});

我认为你的问题是你说你的"get"方法(id)有参数,但当你在Lotes.get(..)上进行调用时,你没有给方法"get"一个id

所以,我认为,你的方法调用应该是类似的东西

Lotes.get({id: SOME_Id}, function(response){
    // ...do stuff with response
});

我不完全确定这种语法,因为我个人更喜欢$q服务,因为它提供了更多的灵活性,但这就是代码的问题所在。通常,你没有给你的方法提供它需要的参数(id)。

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