Angular2 组件的“this"执行回调函数时未定义 [英] Angular2 component's "this" is undefined when executing callback function
问题描述
我有一个组件,它调用服务从 RESTful 端点获取数据.该服务需要在获取所述数据后获得回调函数才能执行.
I have a component which calls a service to fetch data from a RESTful endpoint. This service needs to be given a callback function to execute after fetching said data.
问题是当我尝试使用回调函数将数据附加到组件变量中的现有数据时,我得到一个 EXCEPTION: TypeError: Cannot read property 'messages' of undefined
.为什么 this
未定义?
The issue is when I try use the callback function to append the data to the existing data in a component's variable, I get a EXCEPTION: TypeError: Cannot read property 'messages' of undefined
. Why is this
undefined?
TypeScript 版本:1.8.10 版
TypeScript version: Version 1.8.10
控制器代码:
import {Component} from '@angular/core'
import {ApiService} from '...'
@Component({
...
})
export class MainComponent {
private messages: Array<any>;
constructor(private apiService: ApiService){}
getMessages(){
this.apiService.getMessages(gotMessages);
}
gotMessages(messagesFromApi){
messagesFromApi.forEach((m) => {
this.messages.push(m) // EXCEPTION: TypeError: Cannot read property 'messages' of undefined
})
}
}
推荐答案
使用 Function.prototype.bind 函数:
getMessages() {
this.apiService.getMessages(this.gotMessages.bind(this));
}
这里发生的情况是您将 gotMessages
作为回调传递,当它被执行时,范围是不同的,所以 this
不是您所期望的.bind
函数返回一个绑定到您定义的 this
的新函数.
What happens here is that you pass the gotMessages
as a callback, when that is being executed the scope is different and so the this
is not what you expected.
The bind
function returns a new function that is bound to the this
you defined.
当然,您可以使用 箭头函数 还有:
You can, of course, use an arrow function there as well:
getMessages() {
this.apiService.getMessages(messages => this.gotMessages(messages));
}
我更喜欢 bind
语法,但这取决于你.
I prefer the bind
syntax, but it's up to you.
用于绑定方法的第三个选项:
A third option so to bind the method to begin with:
export class MainComponent {
getMessages = () => {
...
}
}
或
export class MainComponent {
...
constructor(private apiService: ApiService) {
this.getMessages = this.getMessages.bind(this);
}
getMessages(){
this.apiService.getMessages(gotMessages);
}
}
这篇关于Angular2 组件的“this"执行回调函数时未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!