为什么这个对象$ window在有角度的http promise对象中

时间:2016-08-10 21:18:09

标签: javascript angularjs

考虑以下角度服务:

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"。

但是第二个控制台日志将此作为$ window对象返回。两个问题:

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

1 个答案:

答案 0 :(得分:1)

这是因为您在创建传递给promise then方法的函数时创建了新的上下文:

 then(  function( response ) // new function context

您需要将该函数绑定到您需要的对象。

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

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