0
http:Http;

constructor(http:Http){
this.http = http;
}  

myFunction(){

//this.http works great here!

      this.providerobject.getSomething( function(err, result) {

      //this.http here is undefined! I need to use it here

.
.
.

With the code shown above I am trying to make an http request inside of the provider.getSomething function, but it seems the this.http object is undefined here! How can I make an http call inside of this function? I know it has somehting to do with scope as this object works outside of the provider.getSomething function. I do not know how to pass it in though. Say I do this:

 this.providerobject.getSomething(this.http, function(err, result) {

Well that would pass it into my provider function, but not this function. How can I use this object in that scope?

user2924127
  • 6,034
  • 16
  • 78
  • 136
  • 1
    Possible duplicate of [How to access the correct \`this\` / context inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – Patrick Evans May 20 '16 at 05:00
  • I don't work with Angular 2, but in most cases like these, the [Function.bind()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) works well. – Jhecht May 20 '16 at 05:01

1 Answers1

2

there are two approach,

you may store this into some variable say self and use it,

 let self = this;
 

or you may use fat arrow syntax, which takes care of this

let myFunction = ()=>{
   // this will be preserved here,
   this.providerobject.getSomething(this.http, function(err, result) 
}
Madhu Ranjan
  • 17,334
  • 7
  • 60
  • 69