Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 subscribe understand arrow function

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;
            }

        );
like image 871
miholzi Avatar asked Nov 25 '16 09:11

miholzi


People also ask

What does => mean in coding?

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) {...} .

What is subscribe in angular?

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.

Can we call arrow function before declaration?

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.

What is the difference between arrow function and normal function?

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.


1 Answers

  1. Arrow function is anonymous and doesn't bind its own this. Hence, this is this of current context.

  2. 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)
    );
like image 150
Quy Tang Avatar answered Sep 19 '22 07:09

Quy Tang