2015-11-13 9 views
0

我正在處理一個角度項目,並且第一次使用$資源。我現在有隻是作爲一個測試得到的數據出來我的數據庫中有一個調用$資源

這是我服務的服務:

(function() { 
"use strict"; 
angular.module("commonServices") 
    .factory("ptaResource", 
    ["$resource", ptaResource]); 

function ptaResource($resource) { 
    return $resource("http://localhost:55928/api/excercises", {}, { 'query': { method: 'GET', isArray: true } }); 
} 
})(); 

我的問題是這樣的。我對這些控制器中的各種控制器和方法進行了大量調用。我不能換我圍​​繞如何構建服務,使頭我與端點調用它上市

我試圖做這樣的事情:

var services =[ 
    getExercises: getExercises, 
    doSomething: doSomething 
    ]; 
    return service; 

    function getExercises(){ 
     return $resource request here 
     } 

但沒有工作,我已經看過上線但是任何教程只會公開每種類型的請求中的一種。我將向控制器發送多個獲取請求,其中一些請求使用不同的查詢字符串。我也會查詢不同的控制器。我的純粹主義者告訴我,所有這一切都屬於一個地方。

什麼是一個很好的方法來完成這一個大型服務的方式來分別調用每個請求。我應該將它們分解爲每個web api控制器的服務。任何輸入將不勝感激。

感謝, 約翰

回答

1

如果你想換你的資源在一個服務,你可以做這樣的事情:

angular 
    .module('commonServices', ['ngResource']) 
    .factory('ptaResource', ['$resource', function($resource) { 
     return $resource('http://localhost:55928/api/excercises/:excerciseId', { 
      excerciseId: '@id' 
     }); 
    }]) 
    .service('CommonService', ['ptaResource', function(ptaResource) { 
     return { 
      getExercises: function() { 
       return ptaResource.query().$promise; 
      } 
     }; 
    }]); 

然後,你可以把它像這樣:

angular 
    .module('app', ['commonServices']) 
    .controller('SomeController', ['$scope', 'CommonService', function($scope, CommonService) { 
     $scope.exercises = CommonService.getExercises(); 

     // or 
     CommonService.getExercises().then(function(exercises) { 
      $scope.exercises = exercises; 
     }).catch(function(err) { 
      // handle error here 
     }); 
    }]); 
+0

好吧我正在關注你,現在我正在使用我的控制器來調用查詢,但是你正在調用查詢的工廠調用下添加一個服務。然後控制器調用命名函數。我是否正確? – Guyute

+0

這是正確的。說實話,這是沒有必要的額外服務,但我的印象是,這就是你正在努力完成 –

+0

謝謝,使很多道理 – Guyute

相關問題