在 Angular 中将 JavaScript 函数转换为$http提供程序

Converting javascript function into $http provider in Angular

本文关键字:http 程序 转换 Angular 中将 JavaScript 函数      更新时间:2023-09-26

我有以下函数,我正在尝试使用$http提供程序重写该函数。文档显示了许多不同的方法,我无法正确处理。这是函数:

function Ingest(Filename, ID, baseUrl, logger){       
  var url = baseUrl + '/php/' + 'Ingest.php';                                                                
  var dataString = 'Filename=' + encodeURIComponent(Filename) + '&ID=' + encodeURIComponent(ID);
  $.ajax({
    type: "POST",
    url: url,
    async: true,
    cache: false,
    data: dataString,
    success: function(results){                  
        logger.success('Ingestion process has been finished.', '', 'Success');                                                                                 
    }
    //fail
    , error: function (jqXHR, textStatus, errorThrown){
        alert("error:'r'n" + errorThrown);
    }            
  });
}

下面是$http代码的示例:

$http({
method: 'POST',
url: config.appBaseUrl + '/php/' + 'Ingest.php',
data: { ID: encodeURIComponent(ID), Filename: encodeURIComponent(Filename) }
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
}, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});

谢谢

在第一个样本中,你做一个帖子,在第二个样本中做一个get。

您可以使用$http提供的快捷方式方法。

$http.post( config.appBaseUrl + '/php/' + 'Ingest.php',  Filename: encodeURIComponent(Filename), ID: encodeURIComponent(ID)).then(function(response){
}, function(rejection){
});

如果要为$http(标头,...)设置一些特定的配置,请使用函数的第三个参数。

请注意,快捷方式 post/put 有第二个参数用于请求正文,第三个参数用于配置。删除和获取没有请求正文参数,因此配置是函数的第二个参数。