简体   繁体   English

如何在angularjs中将$ http请求转换为$ resource请求

[英]How to convert $http request into $resource request in angularjs

I have this http request, working fine. 我有这个http请求,工作正常。

Controller 控制者

$scope.removeRow = function (od){
  var temp = "order_id=" + od.order_id + "&product_id=" + od.product_id + "&variant_id=" + od.varient_id;
  var req = $http({
      method: 'POST',
      url: 'http://<domain name>/api2/v1/delete_item_in_order',
      data: temp,
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}
  });

  req.then(
      function (response) {
          alert('success')
      },
      function (error) {
          //$scope.details = response.data;
          alert(error.message);
      }
  ); 
}

Service code to get resource object: 获取资源对象的服务代码:

sampleApp.factory('Order', function ($resource) {
   return $resource('http://<domain name>/api2/v1/orders/:id', {id: '@_id'},    {
      'get': {method:'GET'}

    });

});

Question

How to add custom method removeRow in Order service, such that I can use $resource instead of $http in $scope.removeRow() in controller? 如何在Order服务中添加自定义方法removeRow ,以便我可以在控制器的$scope.removeRow()中使用$resource而不是$http

Rather than returning a single function, you can return an object with as many methods in following way 您可以通过以下方式返回具有多个方法的对象,而不是返回单个函数

sampleApp.factory('Order', function ($resource) { 

    var removeRow = function() {console.log()};
    var getResource = function)() {
        $resource('http://<domain name>/api2/v1/orders/:id', {id: '@_id'}, { 'get': {method:'GET'} }); 
    } 

    return { removeRow : removeRow, 
        getResource : getResource
    } 
});

There is no need to specify the get method inside $resource, this is already predefined. 无需在$ resource中指定get方法,该方法已经预定义。

Factory: 厂:

sampleApp.factory('Order', function ($resource) {
    return $resource('http://<domain name>/api2/v1/orders/:id', {id: '@_id'}, null}).$promise;
});

Calling Method: 调用方法:

$scope.removeRow = function (od){
    var temp = "order_id=" + od.order_id + "&product_id=" + od.product_id + "&variant_id=" + od.varient_id;

    Order.save(temp).then(function(result){
        alert('success');
    }, function(err){
        alert(err.message);
    });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM