1

在下面的示例中,$http.get().success()调用中的上下文是undefined. 我想这是因为我使用“使用严格;” 这success()是一个常规功能。

但是我需要在函数调用中访问服务的上下文。实现这一目标的正确方法是什么?

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

2 回答 2

2

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.

于 2013-10-17T17:13:58.877 回答
0

你必须使用角度承诺来实现这一点。

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

我创建了一个 plunkr 来玩: http ://plnkr.co/edit/r7Cj7H

于 2014-04-09T20:10:01.413 回答