【问题标题】:Returning complete response object in promise of $http在 $http 的承诺中返回完整的响应对象
【发布时间】:2016-03-01 23:18:46
【问题描述】:

我在我的一项服务中使用此方法进行 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;
};

基本上这工作正常,但最近我需要代码中的标头数据来获取错误消息以防出现异常。我很困惑如何在返回的承诺中获取该信息。上述函数在调用时仅返回数据,其余 4 项未定义。我相信 promise 无法解决上述多个项目。

那么我如何在promise中返回对象以获得API返回的对象的全部信息。 (正如文档所说,响应包含 5 个字段,数据、状态、标题、配置、状态文本)。

需要帮助..

【问题讨论】:

  • 在解决或拒绝承诺之前,您是否尝试过注销其他参数(数据、状态、标题、配置、状态文本)?他们是否正确注销?
  • 我正在注销数据和状态,是的,它们在此服务方法中打印得很好。
  • 看看@Thomas 解决方案,这是一个好方法:$http.post 本身已经返回了一个承诺,所以你应该避免使用$q.defer() - 也称为deferred antipattern

标签: angularjs angularjs-http


【解决方案1】:

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

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

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.

【讨论】:

  • 我错过了$http.post 已经返回了promise。你是对的,你的解决方案是最好的,避免Deferred antipattern
猜你喜欢
  • 2019-11-17
  • 1970-01-01
  • 2020-01-04
  • 1970-01-01
  • 2016-11-28
  • 2017-02-01
  • 2017-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多