1

hi working on my first angular project and i've run into this problem with not being able to see a value from the service im using in one of my controllers.

also the characterService.query() is fine just the value of errorMessage is not showing up

thanks for your help

Service:

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;
        }
      }
    }

});

}]);

controller:

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();

}]);
  • create a plunker to replicate the issue , add your view code also – Sajeetharan Jul 21 '16 at 16:13
0

There is no need to use an error interceptor. To get the error response from an ngResource query, use the .catch method on its $promise property.

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

From the Docs:

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

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.