无法访问其中的角度组件的属性

时间:2017-12-14 12:30:10

标签: angular typescript angular-material2

尝试在小吃店中显示SSE事件。问题是我无法访问EventSource的snackBar函数内的onMessage属性。 浏览器控制台中显示的错误是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
     });
  }
}

2 个答案:

答案 0 :(得分: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块内访问

-verbose:gc\   -XX:+PrintGCTimeStamps\   -XX:+PrintGCDateStamps\   -XX:+PrintGCDetails\   -XX:+PrintGC\   -Xloggc:logs/gc-api.log\   #-XX:+PrintTenuringDistribution\ #optional   #-XX:+PrintGCApplicationStoppedTime\ #optional 对象。

答案 1 :(得分: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
   });
 }

另一个有效但又讨厌的人是在输入self时创建变量ngOnInit并使用它来维持对适当范围的引用。

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

第一种是更好的解决方案,但要么会做你需要的。