Rafael Baptista Rafael Baptista - 2 months ago 10x
AngularJS Question

Why is this object $window in angular http promise object

Consider the following angular service:

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!

In the first console.log, before the angular promise object created "this" is the service object itself, as expected. That is, it will have a key "someArray".

But the second console log return this as the $window object. Two questions:

  1. Why is this $window, and not the service object?

  2. how do I pass the service object into the $http promise?


It's because you created a new scope when you created the function passed to the promise then method:

 then(  function( response ) // new function scope

You'll need to bind that function to the scope you need.

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

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