Scope of a service

1

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

  

this.retrieveToken is not a function.

Apparently the scope of error handling is not the same as the service, so it 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... };
}]);
    
asked by anonymous 20.07.2017 / 21:34

2 answers

0

In javascript, when we want to reference the proper object (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... 
    };

}]);
    
21.07.2017 / 00:19
1

The problem there is the scope.

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

See 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><divng-app="app" ng-controller="mainController"></div>
    
20.07.2017 / 21:43