简体   繁体   中英

Angular : Cannot read property 'on' of undefined

I'm trying to use websockets in my Angular application with data table component

On every add I run conect() function to update content on the client side.

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

I get this error on the line this.socket.on.. :

Uncaught TypeError: Cannot read property 'on' of undefined

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM