Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular change Socket.io url on runtime

I have my app.module.ts like this:

// Imports
import { SocketIoModule, SocketIoConfig } from './../../node_modules/ngx-socket-io';
const config: SocketIoConfig = {
  url: 'http://192.168.0.101:3000',
  options: {}
};

@NgModule({
  declarations: [AppComponent],
  imports: [
    // modules..
    SocketIoModule.forRoot(config)
  ],
  //..
})
export class AppModule {}

Would like to be able to change the config.url value. But i've no clue how to do it since changing the config.url value doesn't change it on SocketIoModule.forRoot(config) after initialization.

like image 347
SixPlaah Avatar asked Jun 08 '26 17:06

SixPlaah


1 Answers

Just like @03c7c0ace395d80182db07ae2c30f0 said.

Solution: The config in app.module.ts be like

let config: SocketIoConfig = {
  url: 'http://192.168.43.142:9780',
  options: {},
};

and made a service to handle the URL change (in this code only port change but should be same):

import { Injectable } from '@angular/core';
import { Socket, SocketIoConfig } from './../../../node_modules/ngx-socket-io';

@Injectable({
  providedIn: 'root',
})
export class SocketService {
  config: SocketIoConfig = {
    url: 'http://192.168.43.142:9780',
    options: {},
  };

  constructor(private socket: Socket) {
    this.socket = new Socket(this.config);
  }

  changeToAdminSocket() {
    this.socket.disconnect();
    this.config.url = 'http://192.168.43.142:9781'; // Note the port change
    this.socket = new Socket(this.config);
  }
}
like image 160
SixPlaah Avatar answered Jun 11 '26 12:06

SixPlaah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!