Angular2订阅了解箭头功能

mih*_*lzi 7 javascript typescript arrow-functions angular

我尝试通过Angular 2 Observable subscribe方法的例子来理解typescript的箭头函数.有人可以解释我:

我有这个代码有效:

 this.readdataservice.getPost().subscribe(
            posts => { this.posts = posts; }
        );
Run Code Online (Sandbox Code Playgroud)

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

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

        );
Run Code Online (Sandbox Code Playgroud)

Quy*_*ang 11

  1. 箭头函数是匿名的,不绑定自己的this.因此,thisthis当前上下文的.

  2. this如果我们不明确地绑定它,则正常函数绑定到调用者


然后

    this.readdataservice.getPost().subscribe(
        posts => { this.posts = posts; }
    );
Run Code Online (Sandbox Code Playgroud)

    var self = this;
    this.readdataservice.getPost().subscribe(
        function(posts) { self.posts = posts; }
    );
Run Code Online (Sandbox Code Playgroud)

要么

    this.readdataservice.getPost().subscribe(
        function(posts) { this.posts = posts; }.bind(this)
    );
Run Code Online (Sandbox Code Playgroud)


Gün*_*uer 6

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

如果使用箭头函数,则this继续指向定义它的类.

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

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

    );
Run Code Online (Sandbox Code Playgroud)

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