考虑以下角度服务:
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对象返回。两个问题:
答案 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));