AngularJS-在promise.then块中捕获$ q.reject

svu*_*ala 1 javascript angularjs

在我的Angularjs应用程序中,我试图捕获其中一个promise块中的$ q.reject,但无法执行此操作.

在下面的代码中,我拒绝了响应,如果响应返回空数据,我需要在其中一个promise块中捕获被拒绝的响应,并使用$ state进行一些重定向.目前它没有进入$ q.reject()成功块的错误块.

有没有办法将$ q.reject捕获到promise块?

    x.retrieve=function(id){
         return $http.get(url);
    }


  var promise=x.retrieve(id);
  promise.then(
       function(response){
        if($.isEmptyObject(response.data)){
           return $q.reject(response);
        }
       y.push({x:a});
     },function (rejection) {
       $state.go("detail");
     }
 );
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

谢谢.

rye*_*lar 5

请尝试以此格式更改它.

promise.then(function(response){
  if($.isEmptyObject(response.data)){
    return $q.reject(response);
  }
  y.push({x:a});
}).catch(function (rejection) {
  $state.go("detail");
});
Run Code Online (Sandbox Code Playgroud)

更新:对于IE,你可以这样做:

promise.then(function(response){
  if($.isEmptyObject(response.data)){
    return $q.reject(response);
  }
  y.push({x:a});
})['catch'](function (rejection) {
  $state.go("detail");
});
Run Code Online (Sandbox Code Playgroud)