Angular:无法阅读' on'未定义的

时间:2018-01-20 02:05:51

标签: javascript angular datatable angular-material

我试图在我的Angular应用程序中使用带有数据表组件

的websockets

在每次添加时,我运行conect()函数来更新客户端上的内容。

import * as io from "socket.io-client";

@Component({
  selector: "app-liste-projets",
  templateUrl: "./liste-projets.component.html",
  styleUrls: ["./liste-projets.component.css"]
})
export class ListeProjetsComponent implements OnInit {
  constructor(private ajoutProj: AjoutprojService) {}
...


}
export class UserDataSource extends DataSource<any> {

  constructor(private ajoutProj: AjoutprojService) {
    super();
  }
  socket = io('http://127.0.0.1:8080');

  connect():Observable<NouveauProjet[]> {
    var data= this.ajoutProj.getAllProj();

    return data;

  }
  this.socket.on("add", ()=>{
    this.connect()      })
}

我在第this.socket.on..行上收到此错误:

Uncaught TypeError: Cannot read property 'on' of undefined

1 个答案:

答案 0 :(得分:2)

试试这个

export class UserDataSource extends DataSource<any> {
   private socket: SocketIOClient.Socket;
  constructor(private ajoutProj: AjoutprojService) {   
    super();

  }
  connect():Observable<NouveauProjet[]> {
    this.socket = io.connect('http://127.0.0.1:8080')
    this.socket.on('connect', () => {
            console.log('WidgetSocket: Opened a new socket connection', this.socket.id);
    });
    var data= this.ajoutProj.getAllProj();
    return data;
  }
}