I am calling IO of socket.io-client in my angular project like below:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/internal/Observable';
import * as io from 'socket.io-client';
@Injectable({
providedIn: 'root'
})
export class SocketclientService {
socket:any;
url:any="ws://localhost:8080"
constructor() {
this.socket = io(this.url);
}
listen(eventname:any,data:any){
return new Observable((subscriber)=>{
this.socket.on(eventname,(data:any)=>{
subscriber.next(data);
})
})
}
emit(eventname:string,data:any){
this.socket.emit(eventname,data);
}
}
But I am always getting an error like:
Error: src/app/services/socketclient.service.ts:11:19 - error TS2349: This expression is not callable.
Type 'typeof import("C:/somepathtoproject/node_modules/socket.io-client/build/index")' has no call signatures.
11 this.socket = io(this.url);
~~
I am not getting it why this is showing, even I have installed @types/socket.io-client
Library socket.io-client is not compatible with latest Angular 6. There is error at execution time: ReferenceError: global is not defined at Object../node_modules/socket.io-client/node_modules/socket.io-parser/is-buffer.js (is-buffer.js:4)
If we are using a library that assumes these globals are present ( socket.io-client in our case), you can try manually shimming it inside your polyfills.ts file: Adding this line to your polyfills.ts file would fix the issue and your app would be working again.
ngx-socket-io is an Angular wrapper over Socket.IO client libraries. Then, use the @angular/cli command to generate a document model, a document-list component, a document component, and a document service: ng generate class models/ document --type = model ng generate component components/ document-list
If your are using Angular 6 and above, you might run into this error. This is because on version 6 of Angular CLI Angular team removind the shim for global and other node built-ins.
In angular 10 works fine:
import {io} from 'socket.io-client';
This is the official documentation https://socket.io/docs/v3/client-api/index.html
That may be caused by the type definitions been installed separately. But they are shipped with the socket.io-client
package now (see docs: "Note for TypeScript users").
So just uninstall them and change the imports:
npm uninstall @types/socket.io-client
import { io, Socket } from 'socket.io-client';
I found a workaround for this, I explored the socket.io-client modules a bit and under 'index.d.ts' I found this line:
export { lookup as io, Socket, SocketOptions };
So I tried importing like this:
import {io} from 'socket.io-client/build/index';
then to use it:
this.socket=io(url);
it worked for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With