Angular2订阅了解箭头函数

时间:2016-11-25 09:38:29

标签: javascript angular typescript arrow-functions

我试图通过 Angular 2 Observable subscribe方法的例子来理解打字稿的箭头函数。有人可以解释一下:

我的代码有效:

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

但如果我使用它,它应该是一样的吗?但这不起作用。

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

        );

2 个答案:

答案 0 :(得分:10)

  1. 箭头功能是匿名的,不会绑定自己的this。因此,this是当前上下文的this

  2. 如果我们没有明确地绑定它,正常功能会将this绑定到来电

  3. 然后

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

    可以

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

    或者

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

答案 1 :(得分:6)

JS默认执行调用者范围内的函数。如果你传递一个函数来在其他地方调用,this指向调用者。 在您的代码中,您通过subscribe(...)方法将函数传递给observable,然后在发出事件时由observable调用该函数。

如果使用箭头功能,则this会一直指向定义它的类。

另一种方法是使用.bind(this)告诉JS this应该继续指向当前的类实例。

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

    );

另见https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions