2013-08-30 82 views

回答

11

您可以使用resources或者構建實現http調用的服務。

如果你想使用的資源,請記住:

  1. 以包括角resource.js文件,你可以找到here
  2. 在你的模塊聲明,包括像這樣的ngResource模塊依賴於包括:angular.module('myApp',['ngResource'])

之後,你可以用這種方式宣告的資源:

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

另外,如果你需要的粒度這樣的一個更深層次的如

angular.module('myApp') 
.factory('MyAPIService', function($http){ 
    var apiurl, myData; 
    return { 
    getData: function(){ 
     $http.get(apiurl) 
     .success(function(data, status, config, headers){ 
     myData = data; 
     }) 
     .error(function(){ //handler errors here 
     }); 
    }, 
    data: function() { return myData; } 
    }; 
}); 

我找到服務,因爲共享控制器之間的數據的能力是巨大的,所以你可以像一個控制器注入他們使用的服務所以

myapp.controller('MyController', function($scope, MyAPIService){ 
    $scope.data = MyAPIService.data(); 
    // etc. 

}); 
+2

我會參考資源,因爲它們是爲此目的而製作的。 – maxdec

+3

@maxdec是的,資源是爲了這個目的而設計的,但並不是所有的API都是關於某些對象/模型的CRUD。還有更復雜的情景會被資源牽強。 –

+0

我同意,但我們談論的是一個REST API,REST API的主要原則是[提供資源訪問](http://en.wikipedia.org/wiki/Representational_state_transfer#Central_principle),它會使感覺使用[$資源](http://docs.angularjs.org/api/ngResource.$resource)服務:-) – maxdec

1

只要你使用$ HTTP服務它沒有真正使任何區別

雖然供應商的方法其中規定,你應該有一個在客戶端數據提供程序以及服務器端

對於這件事,我建議一個工廠暴露你想要的方法,並利用$ http服務本身

3

這是我們如何做這個,寫http服務作爲factory方法。

市價修改意見使用Promise API

var MyApp = angular.module('App', []); 

MyApp .factory('ApiFactory', ['$http', 
     function ($http) { 
      return { 
       getUsers: function (rowcount) { 
       var promise = $http.get('api/Users/' + rowcount) .then(function(response) { 
       return response.data; 
       }, function (error) { 
       //error 
      }) 
      return promise; 
      } 
     } 
     } 
    ]); 

現在你可以在controller因爲這樣使用它。

MyApp .controller('MyController', ['$scope', 'ApiFactory', 
    function ($scope, ApiFactory) { 

    $scope.Users = null; 

    ApiFactory.getUsers(count).then(function(data) 
    { 
     $scope.Users = data; 
    }); 
} 
]); 
+1

我不會將$ http承諾傳遞給控制器​​。我更喜歡處理服​​務中的錯誤(這裏是ApiFactory),然後解析承諾請求結果,返回data.data – b1r3k

+0

@ b1r3k感謝您的建議 – ssilas777

+0

關於通過$ resource調用REST應該說些什麼? – unknownbits

2

您可以使用restangular https://github.com/mgonto/restangular

你要給你的API這樣的:

// Only stating main route 
Restangular.all('accounts') 

// Stating main object 
Restangular.one('accounts', 1234) 
1

如果你打算使用一個以上的控制器,REST API調用最好是創建一個作爲依賴注入到需要它的控制器的服務。如前所述,您希望使用$ resource來處理RESTful API。

索引。HTML:

<!-- Include Angular and angular-resources --> 
<script src="angular.js"></script> 
<script src="angular-resource.js"></script> 

<!-- Set up your angular module --> 
<div ng-app="RESTfulServiceExample"> 
    <div ng-controller="HomeController"> 
     <ul> 
      <li ng-repeat="game in games">{{game.GameName}}</li> 
     </ul> 
    </div> 
</div> 

<script> 
    // Inject angular-resource as ngResource into your module 
    var gameListApp = angular.module('RESTfulServiceExample', ['ngResource']); 

    // Create a service to call API which can be used by many controllers 
    gameListApp.factory('GameService', ['$resource', function($resource) { 
     return $resource('/game/:gameId', {gameId: '@id'}); 
    }]); 

    // Create a controller that uses your service 
    gameListApp.controller('HomeController', function($scope, GameService) { 
     // GET: /game/ 
     var games = GameService.query(); 

     // Use response in HTML template 
     $scope.games = games; 
    }); 

    // Another controller could use the same service 
    gameListApp.controller('GameController', function($scope, GameService) { 
     // use GameService for another purpose 
    }); 
</script> 

參考:AngularJS: $resource

11

這裏就是我會認爲是最佳做法:

  • 使用工廠服務來處理訪問的機制,以REST風格的Web API
  • 進樣出廠服務進入需要訪問的控制器
  • 在工廠使用承諾到resolv e拒絕來自$ http呼叫的響應
  • 該承諾允許控制器確定應該如何響應RESTful呼叫的結果。例如,它可能需要調用Toast彈出窗口來通知用戶任何問題。

這保持了數據服務層,業務邏輯和前向UI之間的良好分離。它還限制了對任何一層的改變對其他層的任何後果。

+3

感謝解釋@John Kelleher ..但它會更清楚當你給每個例子 – vineet

相關問題