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:无法读取未定义的属性'messages'
。为什么此
未定义?
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
作为回调,当执行该范围时,范围不同,因此此
不是您所期望的。
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.
当然,您可以使用箭头功能:
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屋!