繁体   English   中英

在$ http.get调用中获取服务上下文

[英]Get the service context inside a $http.get call

在下面的示例中, $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
        });
    }
});

通常,您将设置一个上下文变量:

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

我知道jQuery的$.ajax具有context属性,不确定Angulars $http是否存在类似的东西,所以这就是我一直在做的事情。

您必须使用有角度的承诺来实现这一目标。

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

我创建了一个可与以下设备一起使用的插件: http ://plnkr.co/edit/r7Cj7H

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM