Javascript Angular2 组件的“this”在执行回调函数时未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38245450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular2 component's "this" is undefined when executing callback function
提问by Michael Gradek
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.
我有一个组件,它调用服务从 RESTful 端点获取数据。该服务需要在获取所述数据后获得回调函数才能执行。
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?
问题是当我尝试使用回调函数将数据附加到组件变量中的现有数据时,我得到一个EXCEPTION: TypeError: Cannot read property 'messages' of undefined
. 为什么是this
未定义的?
TypeScript version: Version 1.8.10
打字稿版本:版本 1.8.10
Controller code:
控制器代码:
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
})
}
}
回答by Nitzan Tomer
Use the Function.prototype.bindfunction:
getMessages() {
this.apiService.getMessages(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.
这里发生的情况是您将 传递gotMessages
为回调,当它被执行时,作用域是不同的,所以这this
不是您所期望的。
该bind
函数返回一个绑定到this
您定义的新函数。
You can, of course, use an arrow functionthere as well:
当然,您也可以在那里使用箭头函数:
getMessages() {
this.apiService.getMessages(messages => this.gotMessages(messages));
}
I prefer the bind
syntax, but it's up to you.
我更喜欢bind
语法,但这取决于你。
A third option so to bind the method to begin with:
第三个选项,以便绑定方法开始:
export class MainComponent {
getMessages = () => {
...
}
}
Or
或者
export class MainComponent {
...
constructor(private apiService: ApiService) {
this.getMessages = this.getMessages.bind(this);
}
getMessages(){
this.apiService.getMessages(gotMessages);
}
}
回答by Michal Kliment
Or you can do it like this
或者你可以这样做
gotMessages(messagesFromApi){
let that = this // somebody uses self
messagesFromApi.forEach((m) => {
that.messages.push(m) // or self.messages.push(m) - if you used self
})
}
回答by rinukkusu
Because you're just passing the function reference in getMessages
you don't have the right this
context.
因为您只是在getMessages
没有正确this
上下文的情况下传递函数引用。
You can easily fix that by using a lambda which automatically binds the right this
context for the use inside that anonymous function:
您可以通过使用 lambda 轻松解决该问题,该 lambda 表达式会自动绑定正确的this
上下文以供在该匿名函数中使用:
getMessages(){
this.apiService.getMessages((data) => this.gotMessages(data));
}
回答by Tài
Please define function
请定义函数
gotMessages = (messagesFromApi) => {
messagesFromApi.forEach((m) => {
this.messages.push(m)
})
}
回答by bharathiraja
I have same issue, resolved by using () =>{ } instead function()
我有同样的问题,通过使用() =>{ } 代替function() 解决