2013-03-19 40 views
1

我想使用ngResource來使用Firebase rest API。此API使用略微不同的網址來檢索館藏與個人記錄。例如,我有我訪問一個集合:如何使用ngResource爲集合和單個記錄指定不同的URL

https://angular-resource-test.firebaseIO.com/systems.json

但如果我要訪問一個單獨的系統,我使用:

https://angular-resource-test.firebaseIO.com/systems/1.json

如何指定一個基於參數資源聲明中的這個URL?

通常我會做這樣的事情

app.factory('System', ['$resource', function($resource) { 
    var System = $resource(
    'https://angular-resource-test.firebaseIO.com/systems/:id.json', 
    {id: "@id"}, 
    {update: {method: "PUT"}} 
); 
    return System; 
}]); 

但失敗的收集,因爲它缺少尾隨上傳.json。或者,當我指定一個適用於集合的URL時,選擇單個行的情況將失敗。看到這個的jsfiddle爲例:

http://jsfiddle.net/D5E6w/15/

回答

1

有兩種方法可以在資源中發送HTTP GET。

  • 得到:希望收到對象
  • 查詢:希望收到陣列

您的API是不是很寧靜也正因爲如此,你將需要2個資源做自己因爲他們使用不同的URI(請參閱Carl的答案)。我不知道你是否可以編輯你的REST服務,但是這樣做的好方法是: https://angular-resource-test.firebaseIO.com/systems/查詢(期望數組) https://angular-resource-test.firebaseIO.com/systems/:id獲得。 (期望的對象)

有了這項服務,你可以使用你的資源:

var System = $resource(
    'https://angular-resource-test.firebaseIO.com/systems/:id', 
    {id: "@id"}, 
    {update: {method: "PUT"}} 
); 

你會做你的電話是這樣的:

+0

謝謝。不幸的是,這是我使用的firebase API的限制。以下是我們最終如何做到的一個例子: http://jsfiddle.net/D5E6w/58/ – cayblood 2013-03-20 20:20:01

0

你的問題應該通過使用IsArray的解決:您所查詢的真實,獲取系統和方法SystemType中。它與你的json在服務器端如何格式化有關。有關擴展討論,請參閱角度文檔。 http://jsfiddle.net/D5E6w/24/

{ 
    update: { method: "PUT" }, 
    query: { method: "GET", isArray: true }, 
    get: { method: "GET", isArray: true } 
} 

這裏是既具有的系統集合和一個記錄工作的例子。請注意每個的isArray值。 http://jsfiddle.net/D5E6w/51/

0

這裏是我與更換整個$解決方案資源URL。我需要這個,因爲我使用HAL休息響應和分頁時,我想要替換整個URL,而不僅僅是參數。

app.factory('$rest', ['$resource', 'HALParser', function($resource, HALParser) { 
    return function($url) { 
     $url = ($url == null) ? 'http://localhost:8000/:type' : $url; 
     return $resource($url, {type: ''}, { 
      update: { method:'PUT' }, 
      get : { 
       method: 'GET', 
       transformResponse: [function(data) { 
        return (new HALParser()).parse(angular.fromJson(data)); 
       }] 
      } 
     }); 
    } 
}]); 

然後,

app.controller('VendorsController', ['$scope', '$rest', 
     function($scope, $rest) { 

     $scope.data = $rest().get({type: 'vendors'}); 

     $scope.create = function() { 
      $rest().save({type: 'vendors'}, {name: $scope.item}); 
     }; 
     $scope.load = function($item) { 
      console.log($item); 
     }; 

     $scope.page = function($url) { 
      $scope.data = $rest($url).get(); 
     }; 
    }]); 

我從我的服務信息簡單地包裹$資源回報與參數的URL功能。

相關問題