为什么这个对象在angular http承诺对象中是$window ?

Why is this object $window in angular http promise object

本文关键字:对象 承诺 window http angular 为什么      更新时间:2023-09-26

考虑以下angular服务:

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中,在angular的promise对象创建之前,"this"是服务对象本身,正如预期的那样。也就是说,它将有一个键"someArray"。

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

  1. 为什么是$window而不是service对象?
  2. 我如何传递服务对象到$http承诺?

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

 then(  function( response ) // new function context

你需要将这个函数绑定到你需要的对象。

var handleResponse = function( response ) {
    console.log( this );
};
$http.get( "/get-stuff" ).then(handleResponse.bind(this));