ngx-socket-io
ngx-socket-io copied to clipboard
How to stop auto web-socket connection and do it manually
How to prevent Socket to autoConnect to socket and do it manually?
In my application, I only need the socket connection when user is logged in, and it is connecting always, and we suspect that it may be affecting on page performance loading time.
Is it possible. Thank you
@aleixfargas i need todo the same. What I had luckily a static injector. You can check this stackoverflow. Then you can inject the service statically like so:
@Injectable({providedIn: 'root'})
export class SocketOne extends Socket {
constructor() {
super({ url: 'http://url_one:portOne', options: {} });
}
}
Do not forget the providedIn. Now you can use it anywhere ondemand...like this
import {AppInjector} from './app-injector';
const SocketOneSvc = AppInjector.get(SocketOne);
@dotnetdreamer Thank you. We finally kept it as is, so the static injector did not work correctly in our case. Anyway, it would be a great feature for this plugin to allow this by default, don't you think? :)
How to prevent Socket to autoConnect to socket and do it manually?
In my application, I only need the socket connection when user is logged in, and it is connecting always, and we suspect that it may be affecting on page performance loading time.
Is it possible. Thank you
It is possibile! Just put in options: { autoConnect: false }
And connect to the socket endpoint manualy!
constructor() {
super({ url: environment.sockApi+ '/customer', options: { autoConnect: false } });
}
// Send manualy connection
sendConnect() {
if (this.ioSocket.connected) {
return;
} else {
this.ioSocket.connect();
}
}
// Disconnect Manuly
sendDisconnect() {
this.ioSocket.disconnect();
}
I needed to change the uri+namespace+auth outside of the constructor, I came up with this ugly workround.
export class MySockeService extends Socket {
auth: any
constructor() {
const auth = {}
super({ url: '/', options: { transports: ['websocket'], autoConnect: false, auth } })
this.auth = auth;
}
later_change_the(uri: string) {
const wsurl = new URL(uri)
const { io } = this.ioSocket
io.uri = wsurl.toString()
io.opts.hostname = wsurl.host
io.opts.port = wsurl.port
io.opts.path = wsurl.pathname + 'optional_namespace'
this.auth['api-key'] = 'because it would be too simple'
this.ioSocket.connect()
}
}