Wednesday, August 5, 2015
In my last post I talked about how AngularJs Factories need to be instantiated first before they are returned to the calling code.
Consider the following TypeScript code:
The problem here is the code that is generated builds a function by creating a prototype and the way this code is structured, "this" is referring to the global lexical scope and not scope of this class. So this.$http is undefined.
Funny thing is I did not originally write the code this way but using Visual Studio and Resharper, the code suggestion asked me if I wanted to change it. Hey! Why not?? Looks cleaner.
Here is the slightly different TypeScript example, this time using arrow function to implement the needed function:
Now the generated getUser function is in my constructor as a closure function and the "this" has been preserved by defining it with the "_this" variable. Plus, I think this approach is easier to read.
I think the point here is that in TypeScript, you should try as much as possible to opt for the arrow functions. As matter of fact, if you go the TypeScript Handbook site, they talk about this in detail.