I try to understand arrow functions of typescript by the example of Angular 2 Observable subscribe method. Could somebody explain me:
I have this code which works:
this.readdataservice.getPost().subscribe(
posts => { this.posts = posts; }
);
but should it be the same if I use this? But this doesn't work.
this.readdataservice.getPost().subscribe(
function (posts) {
this.posts = posts;
}
);
What It Is. This is an arrow function. Arrow functions are a short syntax, introduced by ECMAscript 6, that can be used similarly to the way you would use function expressions. In other words, you can often use them in place of expressions like function (foo) {...} .
Normally Subscription means an arrangement to receive something. Similarly, in Angular applications Observables will be connected to observers and whenever they observe a new value or change in data, they will execute code with the help of Subscription and all the subscribed components will receive the updated outcome.
An arrow function expression is an anonymous function expression written with the “fat arrow” syntax ( => ). Like traditional function expressions, arrow functions are not hoisted, and so you cannot call them before you declare them.
In regular JavaScript functions, arguments keywords can be used to access the passed arguments when the function is invoked. But, arrow functions do not have their own arguments and it uses the arguments from the outer function.
Arrow function is anonymous and doesn't bind its own this
. Hence, this
is this
of current context.
Normal function binds this
to the caller if we don't bind it explicitly
Then
this.readdataservice.getPost().subscribe(
posts => { this.posts = posts; }
);
Can be
var self = this;
this.readdataservice.getPost().subscribe(
function(posts) { self.posts = posts; }
);
Or
this.readdataservice.getPost().subscribe(
function(posts) { this.posts = posts; }.bind(this)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With