【问题标题】:Using $resource data to make quick API call使用 $resource 数据进行快速 API 调用
【发布时间】:2014-06-20 08:39:52
【问题描述】:

来自 Angular 文档:

var cards = CreditCard.query(function() {
       // GET: /user/123/card
       // server returns: [ {id:456, number:'1234', name:'Smith'} ];

       var card = cards[0];
       // each item is an instance of CreditCard
       expect(card instanceof CreditCard).toEqual(true);
       card.name = "J. Smith";
       // non GET methods are mapped onto the instances
       card.$save();
       // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
       // server returns: {id:456, number:'1234', name: 'J. Smith'};

       // our custom method is mapped as well.
       card.$charge({amount:9.99});
       // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
     });

上述代码使用 GET 请求从服务器获取 CreditCard 数组,然后使用 $resource 类方法(如 $save()$delete())自动将 API 调用回服务器。但是,我遇到了两个问题

问题 1

cards 变量需要来自服务器的数组,并且每个card in cards 都可以被视为$resource 并使用上述方法进行 API 调用。但我们的 API 响应始终采用以下格式:

{
  success: true,
  error: null,
  status: 1,
  result: [] // THIS IS THE ACTUAL RESULT
}

其中 result 是实际数据,或者在本例中为 cards 数组。因此,在运行 card.$save() 之类的内容时,使用我们的 API 响应运行相同的代码不会 POST 正确的数据

问题 2

我很好奇是否有可能(并且可能已经自动支持)使用 ng-repeat 绑定到 DOM 的对象完全像在 $resource 调用之后创建的对象一样对待。

例如,假设我有相同的 CreditCards.query() API 调用,它获取一组卡片,然后将它们设置为控制器中的 $scope.cards 变量。然后我的 DOM 中有 ng-repeat="card in cards" 来显示所有卡片。在 DOM 中的每个 card 上,我还想附加一个 ng-click="deleteCard(card)",它将从 $scope.cards 数组 中删除相应的卡片,并使用该特定卡片作为正文向服务器发送 DELETE 请求请求

所以deleteCard() 函数可能看起来像这样:

$scope.deleteCard = function(card) {

    // REMOVE card from the local array
    var index = $scope.cards.indexOf(card);
    if (index > -1) {
    array.splice(index, 1);
    }

    // REMOVE card from the SERVER
    card.$delete() // Will this work?

}

我们可以使用此功能吗?我的猜测是 Angular 会允许这种情况发生

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    问题 1:

    当您使用 $resource 时,您可以覆盖现有方法和/或添加新方法,以便它可以与您的服务器 API 一起使用。

    你会想做这样的事情:

    function transformQueryResponse(data) {
      return JSON.parse(data).result;
    }
    
    $resource('/cards/:card_id', {id: '@id'}, {
        query: { method: 'GET', isArray: false, transformResponse: transformQueryResponse }
    });
    

    他们在documentation for $resource 的底部提供了一个创建自定义 PUT 请求的示例。

    问题 #2:

    是的,您可以这样做。当您从服务器取回 $resource 对象时,当您在 ng-repeat 中使用它们时,它们将继续充当资源。

    【讨论】:

      猜你喜欢
      • 2015-01-17
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多