【问题标题】:Angularjs: How to write $http as promise for controllerAngularjs:如何编写 $http 作为控制器的承诺
【发布时间】:2016-01-23 04:46:21
【问题描述】:

目前我在我的控制器中使用 $http.success().error()。但是,Angular 已弃用成功/错误支持,并且根据样式指南,编写服务器 $http 调用的最佳位置是服务。

鉴于此,我想知道以下代码是否是正确的前进方式。

控制器:

var funcWithPromise = function() {
            // This service's function returns a promise, but we'll deal with that shortly
            TestService.getWeather()
                .then(function(data) {
                    if (data.forecast==='good') {
                        prepareFishingTrip();
                    } else {
                        prepareSundayRoastDinner();
                    }
                }, function(response) {
                    // promise rejected, could log the error with: 
                        $scope.errorDiv = response.data;
                        console.log('error', response);
                        //Manipulate DOM
                    });
            };

服务:

app.factory('TestService', function ($http, $q) {
        return {
            getWeather: function() {
                // the $http API is based on the deferred/promise APIs exposed by the $q service
                // so it returns a promise for us by default
                return $http.get('http://weather')
                    .then(function(response) {
                        return response.data;
                    }, function(response) {
                        // something went wrong
                        return $q.reject(response);  //Not sure is it must be response or reponse.data here. With reponse I can utilize response.status.
                    });
            }
        };
    });

【问题讨论】:

    标签: javascript angularjs http promise


    【解决方案1】:

    按照“官方”文档,你的方法是正确的,所以继续。

    我会做像你这样的事情。这里是官方文档的链接:https://docs.angularjs.org/api/ng/service/$http

    【讨论】:

      【解决方案2】:

      我不会盲目这样做

       $http(..).then(function(response) {
              return response.data;
       });
      

      以上假设所有有效的 HTTP 响应都会变异为数据,但这与您执行此操作时不同。

       $http(..).success(function(data) {
              return data;
       });
      

      $http 中的 success 回调仅在响应状态为 200 系列代码时触发,当您切换到 then 时所有成功的 HTTP 响应(200、300、400 等)作为已解决的响应处理。

      因此,你想做这样的事情。

       return $q(function(resolve,reject){
           $http(..).then(function(response) {
              if(response.status == 200) {
                  resolve(response.data);
              } else {
                  reject(response);
              }
           });
       });
      

      这将仅解析响应中的数据成功的 200 个响应。现在,您的服务返回的承诺只会解析为该数据或被拒绝。

      对于错误处理,我建议你使用拦截器,不要在指令中实现错误处理(除非有特殊情况)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-15
        • 2014-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-14
        • 2015-03-15
        • 1970-01-01
        相关资源
        最近更新 更多