返回完整响应 object 以承诺 $http

Returning complete response object in promise of $http

我的一项服务中使用了此方法来进行 API 调用:

this.postData = function(requestURL, requestObj) {
    var deferred = $q.defer();
    console.log("Reached APIService @POST", requestURL);
    $http.post(requestURL, requestObj).success(
        function(data, status, headers, config, statusText) {
            deferred.resolve(data, status, headers, config, statusText);
            console.log(status);
        }).error(
        function(data, status, headers, config, statusText) {
            deferred.reject(data, status, headers, config, statusText);
            console.log(status);
        });
    return deferred.promise;
};

基本上这工作正常,但最近我需要 headers 我的代码中的数据以在出现异常时获取错误消息。我很困惑如何在返回的承诺中获取该信息。上面的函数在调用时 returns 只有数据和其余 4 项未定义。我相信 promise 不能像上面那样解决多个项目。

那我怎么返回object中的object来获取API返回的object的全部信息。 (正如文档所说,响应包含 5 个字段、数据、状态、headers、配置、statusText)。

需要帮助..

Promise 只能解析为一个值,而不是五个,因此您传递给 resolve 的其余参数将被静默删除。

好消息是 $http.post() 本身已经 returns 一个承诺,所以你可以这样做:

this.postData = function (requestURL, requestObj) {
    console.log("Reached APIService @POST", requestURL);
    return $http.post(requestURL, requestObj).then(
        function (response) {
            console.log(response.status);
            return response;
        }),
        function (response) {
            console.log(response.status);
            throw response;
        });
};

或者,没有日志记录:

this.postData = function (requestURL, requestObj) {
    return $http.post(requestURL, requestObj);
};

response 对象具有 datastatusheaders 等属性。 Documentation.