2016-08-10 68 views
1

考虑以下角度服务:

app.factory('myService', function($http) 
{ 
    var service = 
    { 
     someArray: [], 
     updatePendingIds: function() 
     { 
      console.log(this); 
      $http.get("/get-stuff"). 
       then(function(response) 
       { 
        console.log(this); // someArray is not here! 
       }); 
     } 
    } 
} 

在第一的console.log,产生的角承诺对象之前,“这”是服务对象本身,预期。也就是说,它会有一个关键的“someArray”。

但第二个控制台日志返回这个作为$窗口对象。两个问题:

  1. 为什么这个$ window,而不是服务对象?
  2. 如何将服务对象传递给$ http promise?

回答

1

这是因为您创建了一个新的环境,当你创建传递给承诺then方法的功能:

then( function(response) // new function context 

你需要该功能结合到你需要的对象。

var handleResponse = function(response) { 
    console.log(this); 
}; 

$http.get("/get-stuff").then(handleResponse.bind(this)); 
+0

的作品。也试过以下内容,创建了“handleResponse”函数作为服务的成员,但仍然没有绑定。必须实际调用绑定。例如“handleResponse:function(){...}”,然后是“$ http.get(url).then(this.handleResponse.bind(this));”惊讶的需要“绑定(这)”。为什么? –

+0

@RafaelBaptista这是一个常见的JavaScript误解,因为函数是第一类对象。执行一个函数,范围例如'this.handleResponse()'不同于访问包含函数的对象属性,例如'this.handleResponse'。访问属性为您提供了交给'.then'回调函数的第一类函数,但是当执行回调函数时,它不再具有范围。 (我希望这是有道理的;这个概念很难在评论框中解释:)) – Stephen

+0

其实,我期待的术语是“上下文”而不是范围。这个博客解释得很好:http://ryanmorr.com/understanding-scope-and-context-in-javascript/ – Stephen