Angular2 subscribe understand arrow function

只谈情不闲聊 提交于 2020-01-11 05:09:06

问题


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

        );

回答1:


JS by default executes functions in the scope of the caller. If you pass a function around to be called somewhere else, this points to the caller. In your code you pass the function to the observable via the subscribe(...) method and then the function is called by the observable when an event is to be emitted.

If you use arrow function, then this keeps pointing to the class where it is defined.

An alternative is using .bind(this) to tell JS this should keep pointing at the current class instance.

    this.readdataservice.getPost().subscribe(
        function (posts) {
            this.posts = posts;
        }.bind(this)

    );

See also https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions




回答2:


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


来源:https://stackoverflow.com/questions/40801758/angular2-subscribe-understand-arrow-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!