스낵바에 SSE 이벤트를 표시하려고합니다. 문제 : snackBar
속성의 onMessage
EventSource 함수에 액세스 할 수 없습니다. 브라우저 콘솔에 표시된 오류는 Cannot read property 'open' of undefined
입니다.내부에 각 구성 요소의 속성에 액세스 할 수 없습니다.
import {Component, OnInit} from '@angular/core';
import {MatSnackBar} from '@angular/material';
@Component({
selector: 'snack-bar-overview-example',
templateUrl: 'snack-bar-overview-example.html',
})
export class SnackBarOverviewExample implements OnInit{
constructor(public snackBar: MatSnackBar) {}
ngOnInit() {
//Created a local Server Sent Events server
//which sends timestamp for every 5 second
var source = new EventSource('http://localhost:8000/events');
source.onmessage = function(response){
console.log('test', response.data);
//Could not able to access snackbar
//Error statement is given below
//Cannot read property 'open' of undefined
this.snackBar.open(response.data, 'close', {
duration: 4000
});
}
//Same lines here, have no issues and working perfectly
this.snackBar.open('message', 'close', {
duration: 4000
});
}
}
함수를 만들 때 함수 범위와 관련이 있습니다.이 경우 함수 개체 자체입니다. 굵은 화살표를 사용하여 함수 정의 –