我试图通过 Angular 2 Observable 订阅方法的例子来理解 typescript 的箭头函数。有人可以解释一下吗:
我有这段有效的代码:
this.readdataservice.getPost().subscribe(
posts => { this.posts = posts; }
);
但是如果我用这个应该是一样的吗?但这不起作用。
this.readdataservice.getPost().subscribe(
function (posts) {
this.posts = posts;
}
);
最佳答案
箭头函数是匿名的,不绑定(bind)它自己的
this
。因此,this
是当前上下文的this
。如果我们不显式绑定(bind)它,普通函数会将
this
绑定(bind)到调用者
然后
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)
);
关于javascript - Angular2订阅了解箭头功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40801758/