如何从 ngResource $resource 查询中获取错误响应

How to Get Error Response from ngResource $resource query

嗨,我正在处理我的第一个 angular 项目,我 运行 遇到了这个问题,无法从我的一个控制器中使用的服务中看到值。

characterService.query() 也很好,只是没有显示 errorMessage 的值

感谢您的帮助

服务:

angular.module('characterResource',['ngResource'])

.factory('characterService',['$resource',function($resource){
var self = this;

self.errorMessage = false;

return $resource('http://gateway.marvel.com:80/v1/public/characters?limit=90&apikey=APIKEY',null, {

    query: {
      method: 'GET',
      isArray: false,
      transformResponse: function(data) {
        return angular.fromJson(data).data;
      },
      interceptor:{
        responseError:function(error){
            console.log(error);
            self.errorMessage = true;
        }
      }
    }

});

}]);

控制器:

angular.module('CharactersCtrl', []).controller('CharactersController',['characterService', function(characterService) {
var self = this;
self.sortType     = 'name'; // set the default sort type
self.sortReverse  = false;  // set the default sort order
//self.search  = ' ';     // set the default search/filter term

self.errorMessage = characterService.errorMessage;
console.log(characterService.errorMessage);

self.init = function(){
    self.getCharacters();
}

self.getCharacters = function(){
    self.characters = characterService.query();
}

self.init();

}]);

不需要使用错误拦截器。要从 ngResource 查询中获取错误响应,请在其 $promise 属性.

上使用 .catch 方法
self.getCharacters = function(){
    self.characters = characterService.query();
    self.characters.$promise.catch( function(errorResponse) {
        console.log(errorResponse);
        self.errorMessage = true;
    });     
}

来自文档:

The Resource instances and collections have these additional properties:

  • $promise: the promise of the original server interaction that created this instance or collection.

On success, the promise is resolved with the same resource instance or collection object, updated with data from server. This makes it easy to use in resolve section of $routeProvider.when() to defer view rendering until the resource(s) are loaded.

On failure, the promise is rejected with the http response object, without the resource property.

--AngularJS $resource Service API Reference