简体   繁体   English

Angular2 组件的“this”在执行回调函数时未定义

[英]Angular2 component's “this” is undefined when executing callback function

I have a component which calls a service to fetch data from a RESTful endpoint.我有一个组件,它调用服务从 RESTful 端点获取数据。 This service needs to be given a callback function to execute after fetching said data.该服务需要在获取所述数据后获得回调函数才能执行。

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 .问题是当我尝试使用回调函数将数据附加到组件变量中的现有数据时,我得到一个EXCEPTION: TypeError: Cannot read property 'messages' of undefined Why is this 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
        })
    }
}

Use the Function.prototype.bind function:使用Function.prototype.bind函数:

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.这里发生的事情是你将gotMessages作为回调传递,当它被执行时,范围是不同的,所以this不是你所期望的。
The bind function returns a new function that is bound to the this you defined. bind函数返回一个绑定到您定义的this的新函数。

You can, of course, use an arrow function there 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);
    }
}

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

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

我有同样的问题,通过使用() => { } 代替function() 解决

Please define function请定义函数

gotMessages = (messagesFromApi) => {
  messagesFromApi.forEach((m) => {
    this.messages.push(m)
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM