2017-12-14 8 views
0

스낵바에 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 
    }); 
    } 
} 
+0

함수를 만들 때 함수 범위와 관련이 있습니다.이 경우 함수 개체 자체입니다. 굵은 화살표를 사용하여 함수 정의 –

답변

1

콜백에서 액세스하려고하므로 잘못된 범위에 있습니다. 이것을 해결할 수있는 두 가지 방법이 있습니다. 첫 번째, 그리고 최고에, 지방 화살표 구문을 사용하는 기존 기능을 수정하는 것입니다 :

source.onmessage = (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 
    }); 
} 

하지만 일부 미움 어떤 작품, 다른, 당신이 당신의 ngOnInit 및 사용을 입력 할 때 변수 self을 생성하는 것입니다 적절한 범위에 대한 참조를 유지해야합니다.

ngOnInit() { 
    const self = this; // here is where you would create it 
    //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 
     // replace this with self here 
     self.snackBar.open(response.data, 'close', { 
     duration: 4000 
     }); 
    } 
    //Same lines here, have no issues and working perfectly 
    self.snackBar.open('message', 'close', { 
     duration: 4000 
    }); 
    } 

첫 번째 방법이 더 나은 방법이지만 두 가지 방법이 필요합니다.

1

를 사용하여 지방 화살표 대신 function()=>.

source.onmessage = (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 
     }); 
    } 

this 목적 function 블록 내부에 접근 할 수 없다.