【问题标题】:Angular2 subscribe understand arrow functionAngular2订阅理解箭头功能
【发布时间】:2016-11-25 09:38:28
【问题描述】:

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

我有这个有效的代码:

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

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

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

        );

【问题讨论】:

标签: javascript angular typescript arrow-functions


【解决方案1】:
  1. 箭头函数是匿名的,不绑定自己的this。因此,this 是当前上下文的this

  2. 如果我们不显式绑定,普通函数会将this 绑定到调用者


然后

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

【讨论】:

    【解决方案2】:

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

    如果你使用箭头函数,那么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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2019-06-25
      • 1970-01-01
      • 2017-10-28
      • 2017-07-29
      • 2016-11-29
      相关资源
      最近更新 更多