2016-06-08 114 views
0

我有這個http請求,工作正常。

控制器

$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); 
     } 
); 
} 

服務代碼來獲取資源對象:

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

    }); 

}); 

問題

如何添加自定義的方法removeRowOrder Servi大街ce,這樣我可以使用$resource而不是$http in $scope.removeRow() in controller?

+1

在這裏看到我的回答(http://stackoverflow.com/questions/36310771/get-data-on-conditions-by-resource -angualrjs/36311255#36311255) –

回答

1

而不是返回一個單一的功能,您可以在以下方式

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 
    } 
}); 
1

返回與儘可能多的方法的對象沒有必要指定$資源中GET方法,這已經是預定義的。

廠:

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

調用方法:

$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); 
    }); 
};