Tôi có một thành phần gọi một dịch vụ để tìm nạp dữ liệu từ một điểm cuối RESTful. Dịch vụ này cần được cung cấp một hàm gọi lại để thực thi sau khi tìm nạp dữ liệu nói trên.
Vấn đề là khi tôi thử sử dụng hàm gọi lại để nối dữ liệu vào dữ liệu hiện có trong biến của thành phần, tôi nhận được a EXCEPTION: TypeError: Cannot read property 'messages' of undefined
. Tại sao this
không xác định?
Phiên bản TypeScript: Phiên bản 1.8.10
Mã bộ điều khiển:
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
})
}
}
tsc -v
)