ionic2 ModalController 无法在 websocket 中显示

ionic2 ModalController can not show in websocket

import { Component } from '@angular/core';
import { NavController, Events, ModalController } from 'ionic-angular';

import * as SockJS from 'sockjs-client';
import { SomePage } from './somepage';

export class DashboardPage {
    sockjs: any;
    constructor(public navCtrl: NavController,
        public events: Events,
        private modalCtrl: ModalController) {

        this.initWebsocket();
    }

    initWebsocket() {
        this.sockjs = new SockJS('http://192.168.0.141:8080/ws-driver');

        this.sockjs.onopen = function () {
            console.log('open');
        };
        this.sockjs.onmessage = function (e) {
            console.log('message', e.data);
            alert('ok');
            let model = this.modalCtrl.create(SomePage);
            model.present();
        };
        this.sockjs.onclose = function () {
            console.log('close');
        };
    }
}

alert('ok') 已处理。 谢谢

使用 arrow functions 而不是 function 关键字,因为 this 在函数中引用 function object。 尝试:

 this.sockjs.onmessage = (e)=> {
            console.log('message', e.data);
            alert('ok');
            let model = this.modalCtrl.create(SomePage);
            model.present();
        };

或设置self=this;

let self = this;
 this.sockjs.onmessage = function (e) {
            console.log('message', e.data);
            alert('ok');
            let model = self.modalCtrl.create(SomePage);
            model.present();
        };