2017-12-14 9 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

コールバックでこれにアクセスしようとしているので、あなたは間違った範囲にいます。これを解決するには2つの方法があります。 、最初に、そして最高の脂肪の矢印構文を使用するために、既存の機能を変更することです:

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ブロック内でアクセスすることができません。

関連する問題