1

I am trying to learn angular with socket in a todo app. But socket is not working. I am using socket.io v2.0.3. but I am getting error in chrome console.

Error screenshot

My code is -

import io from "socket.io-client";
private url = 'http://localhost:3001';
private socket;

ngOnInit(): void() {
    this.socket = io.connect(this.url);
    // Receive Added Todo
    this.socket.on('TodoAdded', (data) => {
    console.log('TodoAdded: '+JSON.stringify(data));
    this.todos.push(data.todo);
  });
}
1
  • Ensure that the declaration private url = 'localhost:3001'; remains the way it is. If you append endpoints directory path name to private url (e.g private url = 'localhost:3001/api/';), you'll not be able to listen to or emit data to the server. Commented Apr 8, 2020 at 20:07

2 Answers 2

5

I think you need to import io like this instead:

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

otherwise you do not know which export to use from socket.io-client. It has no default export.

Side Note: You can use this.socket = io(this.url) instead of using the connect-method if you want to.

Sign up to request clarification or add additional context in comments.

1 Comment

Also ensure that you keep your URL clean. private url = 'localhost:3001';
0

this problem sucked a lot of my energy the solution is very simple . all of you guys who are working in angular6+ and using RxJS 6+ just do this in your polyfills.ts file just add this line

   (window as any).global = window;

hope this solves your problem

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.