【问题标题】:Promise in Angular.jsAngular.js 中的承诺
【发布时间】:2016-01-10 13:30:30
【问题描述】:

我已经更改了我的 url 的 env 属性以在本地测试我的代码。似乎错误回调甚至没有被调用。 我的代码 sn-p-

        $scope.getfiles = function() {
        Api.file.query().$promise.then(
        function(result){ $scope.getfiles = result; },  //on success
        $scope.commonAjaxErrorHandling("Failed to get  File data.",true)  //on failure--> Always this line of  code is executing..
           );
         };

如果我尝试编写其他错误函数。它甚至没有被调用。

        $scope.getfiles = function(){
        Api.flatFile.query().$promise.then(
         function(result){ $scope.File = result; 
  },
      function (result) { // this block is not getting called
         if(result.status== 404){
         $scope.addErrorAlert("Service is down.Please try again later",true);
         return;
     }
 });
};

有人可以帮我解决这种情况吗?

        FileServices.factory('Api', ['$res', '$loc',
        function($res, $loc){
        var contextPath = $loc.absUrl().split('/app/')[0];
        return {
        flatFile: $res(contextPath+'/app/config/flatFile/data', {}, {
        query: {method:'GET', isArray:true},
        save: {method:'POST'},
        })
        };
       }]);

【问题讨论】:

  • 您能否通过开发者控制台验证该函数是否被调用或未对其进行调试。控制台是否有任何错误>
  • 角度承诺库是$q
  • API.file.query()是什么,你想用它实现什么,请提供代码部分。
  • 请看我编辑的帖子..
  • API 是一项服务。并尝试在服务关闭时添加错误警报消息。所以在本地我试图改变 url 的 env 属性。

标签: javascript angularjs angularjs-directive angularjs-scope angular-ui-router


【解决方案1】:

该函数可能不会以任何一种方式被调用。 这里的问题是,在第一种情况下,您没有将函数定义为回调,而是立即调用函数本身

$scope.commonAjaxErrorHandling("Failed to get  File data.",true)

这不是回调定义,而是立即调用 $scope.commonAjaxErrorHandling

所以我的想法是不会发生错误,这就是为什么在第二种情况下也不调用错误函数

【讨论】:

    【解决方案2】:

    您似乎错误地检查了status。 您应该访问fail 回调的第二个参数:

      // ...
      ,
      function (jqXHR, textStatus, error) { 
         if(textStatus == 404){
            $scope.addErrorAlert("Service is down.Please try again later",true);
            return;
       }
     }
    

    注意: 您从Api 服务返回的对象中没有file 键,因此它应该是@987654326 @ 代替。

    【讨论】:

      猜你喜欢
      • 2015-08-06
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      • 2015-10-06
      • 2023-03-26
      相关资源
      最近更新 更多