0

I have an Angular 2 application where I am fetching some data from a remote service. My application is layered into a Components layer and a Services layer. The Services layer communicates with the backend services. A sample interaction is posted below:

this.myServiceClass.getData(param1, param2)
                   .then(res => {
                         this.responseObj = res;
                         this.bindDataToGrid();
                         }

The service getData method returns a Promise where ResponseModel is a View Model class.

The issue is that the statement:

this.responseObj = res;

is throwing an error stating that this is null. So I set it outside the service call as follows:

let this$ = this;

and used this$ in my Promise.then. it works. Question is: It is working for my colleague without the reassignment to this$. For me it is not working even though I am using an arrow function in my code. Any ideas why I need to store a reference to this outside the Promise.then?

enter image description here

Viking22
  • 545
  • 1
  • 7
  • 19
  • can you add more code as in how yyou are using this service, do you have a function inside which you are calling this service? – Madhu Ranjan Sep 27 '17 at 20:31
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Estus Flask Sep 27 '17 at 20:36
  • `this` can't be `null` in the code you've posted. It is equal to `this` that is used in `this.myServiceClass...`. – Estus Flask Sep 27 '17 at 20:39
  • Yes, it is inside another function.. I will try to post an image. – Viking22 Sep 29 '17 at 03:49
  • Added an image. I had to clear out a lot of the sections as per firm policy but it still shows the issue. – Viking22 Sep 29 '17 at 03:58

0 Answers0