Scope of a service

Asked

Viewed 58 times

1

I have a problem in a service of AngularJS, after a consultation REST using RestAngular in return 401, need to be able to call a method of the service in which it is inserted. The problem is that when calling it I get the message:

this.retrieveToken is not a Function.

Apparently the scope of the Handling error is not the same as the service, and so does not recognize the method. Is there a way to do this? My code is currently like this:

util.service('Util',[dependencies... {

  this.buscar = function (addr,options) {
    Restangular.setFullResponse(true);
    var result = Restangular.all(addr).getList(options);
    result.then(function(response){ //success },
    function(error){ 

      //O PROBLEMA ACONTECE AQUI
      this.retrieveToken();

    });
  };
  this.retrieveToken = function (){ //code... };
}]);

2 answers

1

The problem there is the scope.

The this within the then does not refer to the same this that you created the function, remove them or assign this to some variable to reference the external scope.

Take an example:

angular.module('app', []);
angular.module('app').controller('mainController', function($http) {
  var controller = this;
 
  $http.get('http://www.google.com').then(function(){        
  }, function() {
    controller.teste(); // Chamei aqui porque vai dar erro na requisição
  });
  
  this.teste = function(){
    console.log('ahoy');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="mainController"></div>

  • Thanks for the reply! Gave to have a good idea. :)

0


In javascript, when we want to reference the object itself (this) at any depth, we use a local variable to store the reference to this. Ex:

var self = this;

getting:

util.service('Util',[dependencies... {

    var self = this; // visível apenas no escopo do objeto como uma variável local

    this.buscar = function(addr, options) {

        Restangular.setFullResponse(true);

        var result = Restangular.all(addr).getList(options);

        result.then(function(response){ ... }, function(error) { 

            //O PROBLEMA ACONTECE AQUI (não acontece mais)
            self.retrieveToken();

        }); 
    };

    this.retrieveToken = function() { 
        //code... 
    };

}]);
  • Thanks for the answer! : ) I managed to solve.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.