2015-06-10 46 views
0

假設我正在使用angular-resource - 模塊和我的ng-app。我無法理解data處理簡單和可擴展的方式..任何人給我/給我一個正確的方式來回答所有這些問題?角度 - 處理從服務器獲取數據的正確方法?

a)通常如何從角度獲取url中的數據。 b)如果每個控制器可能需要不同的網址和數據(如果有的話)如何在每個控制器上添加fetch進程。

c)或需要我們根據控制器參數提供數據服務 - 如果是的話如何將參數傳遞給服務?

d)以上全部都有GET,PUT,DELETE,'POST`然後如何處理所有這些 - 這一切都需要單獨的服務嗎?

在此先感謝。

回答

1

使用angular-resource正如您在服務/工廠內說的那樣。它已經提供了很多你的要求:

myApp.factory("dataService", [ 
    "$resource", 
    function ($resource) { 
     return $resource("http://someBaseUrl/:action/:id", { 
      id: "@id" // default parameters 
     }, 
     { 
      // custom methods 
      update: { method: "PUT" }, 
      doOtherStuff: { method: "GET", action: "DoOtherStuff" } 
     }); 
    } 
]); 

$resource默認提供了以下REST兼容功能:

{ 
    'get': {method:'GET'}, 
    'save': {method:'POST'}, 
    'query': {method:'GET', isArray:true}, 
    'remove': {method:'DELETE'}, 
    'delete': {method:'DELETE'} 
}; 

你必須包括你自己的任何其他功能,如update並在doOtherStuff上面的例子。

:action部分是一種簡單的方法來提供任何自定義操作,而不是REST兼容。

使用在控制器:

myApp.controller("myCtrl", [ 
    "dataService", 
    function (dataService) { 
     // first parameter can be used for any extra query parameters 
     // second parameter always is a callback 
     var myData = dataService.query({}, function() { 
      // success 
     }); 

     var mySingleInstance = dataService.get({ id: 12 }); 

     this.doUpdate = function (entity) { 
      dataService.update(entity); 
      // Or, if the 'entity' is a resource entity: 
      // entity.$update(); 
     } 

     this.customMethod = function() { 
      dataService.doOtherStuff(); 
     } 
    } 
]); 

https://docs.angularjs.org/api/ngResource/service/ $資源的完整文檔

+0

看起來不錯。順便說一句,如何創建獨立的'指令'我在這裏試過這是不工作:http://jsfiddle.net/ydkezd15/7/ – 3gwebtrain

+0

檢查此更新的jsfiddle http://jsfiddle.net/ydkezd15/8/ – devqon

+0

但它依賴'app'變量正確嗎?我正在尋找'directive'如何轉換成像'component'一樣? – 3gwebtrain

相關問題