我如何访问 .then 函数 AngularJS 中的响应标头



你知道我如何从 get 请求访问响应标头吗?

我有一个返回承诺的服务函数。我的控制器解决了承诺,在 .then 函数中,我需要响应标头中的内容类型。

尝试使用"headers"参数,我用console.log(headers())显示该参数,但是我的控制台中显示的错误"headers()不是函数"。

我的服务 :

.factory('GetResultFile',
['$http', '$q',
function ($http, $q) {
    var service = {};
    service.getResult = function(id, rid) {
        var deferred = $q.defer();
        $http
        .get('http://localhost:9999/v1/jmeter/' + id + '/results/' + rid, {cache: false})
        .then(function(data, status, headers, config) {
            if(data.status == 200) {
                console.log(data.status);
                deferred.resolve(data);
            }
            else {
                deferred.reject(data);
            }
        });
        return deferred.promise;                
    }
    return service;

}]);

控制器:

$scope.getResult = function(rid) {
        console.log($scope.id);
        GetResultFile.getResult($scope.id, rid)
        .then(function(data, headers) {
            //console.log(headers.Content-type);
            console.log(headers());
            console.log(data);
            console.log("Download succeed");
            console.log(data.status);
            var file = new Blob([data.data], {type: 'text/plain;charset=utf-8'});
            FileSaver.saveAs(file, 'test.txt');
        }, function (data) {
            console.log("Download ERROR!");
            console.log(data.status);
        })
    };              

}])

没有更多的信息,我只能考虑标准的东西,比如

    this.$http.get('/your/Route')
      .then(response => {
        console.log(response) // Full information
        console.log(response.data) // holds your Data
        console.log(response.config) // holds more Specific information like the Url and more
        console.log(response.headers());// Specific headers Information
        console.log(response.headers(["content-type"]));//gets the Content-Type of Header
});

一般到角度服务和响应

响应对象具有以下属性:

  • data{string|Object} – 使用转换函数转换的响应正文。

  • 状态{number} – 响应的 HTTP 状态代码。

  • 标头{function([headerName])} – 标头获取器功能。

  • config{Object} – 用于生成请求的配置对象。

  • 状态文本{string} – 响应的 HTTP 状态文本。

https://docs.angularjs.org/api/ng/service/$http

最新更新