Pregunta

In the example below, the context inside the $http.get().success() call is undefined. I suppose it is because I use "use strict;" and that success() is a regular function.

However I need to access the context of the service inside the function call. What is the proper way of achieving this ?

ng_app.service('database', function($http)
{
    this.db = new Db();
    this.load = function()
    {
        console.log(this); // logs the service context correctly
        $http.get('get_nodes/').success(function(ajax_data)
        {
            console.log(this); // logs "undefined"
            console.log(this.db); // throws an exception because this is undefined
            this.db.nodes = ajax_data; // throws an exception because this is undefined
        });
    }
});
¿Fue útil?

Solución

Typically you will set a context variable:

this.db = new Db();
var that = this;
this.load = function()
{
    console.log(this); // logs the service context correctly
    $http.get('get_nodes/').success(function(ajax_data)
    {
        console.log(that); 
        console.log(that.db); 
        that.db.nodes = ajax_data; 
    });

I know jQuery's $.ajax has a context property, not sure if anything like that exists with Angulars $http, so this is what I've been doing.

Otros consejos

You have to use angular promises to achieve this.

angular.module('myapp', [])
  .service('Github', function($http, $q) {
    this.getRepositories = function() {
      var deferred = $q.defer();
      $http.get('https://api.github.com/users/defunkt')
        .success(function(response) {
          // do stuffs with the response
          response.username = response.login + ' ' + response.name;
          // like filtering, manipulating data, decorating data found from from api
          // now pass the response
          deferred.resolve(response);
        }).error(function(response) {
          deferred.resolve(response);
        });
      return deferred.promise;
    }
  })
  .controller('MainCtrl', function($scope, Github) {
    Github.getRepositories().then(function(dt) {
      $scope.user = dt;
    });
  });

I have created a plunkr to play with: http://plnkr.co/edit/r7Cj7H

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top