Cabrra
Cabrra

Reputation: 644

Socket-io dynamic initialization

Problem statement

After implementing socket.io on my Angular app I was curious to learn if I could dynamically set-up the "SocketIoModule" on the client (FrontEnd) app.module file.

I would like load the URL and port from the server (Back-end) config file following the description of the npm package

import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
import { SocketService } from './services/socket.service';
const socketConfig: SocketIoConfig = { url: 'http://localhost:3000', options: {} };

@NgModule({

[..]

imports: [
    BrowserModule,
    SocketIoModule.forRoot(socketConfig)
  ],
providers: [
  // all other providers
  <SocketProvider>
]

[..]

//package.json

   "ngx-socket-io": "^2.1.1",
   "socket.io": "^2.2.0",
   "socket.io-client": "^2.2.0"

Desired end state

//backend config service
let url = config.env.url.base + config.env.url.socketIoPort;
const socketConfig: SocketIoConfig = { url: url, options: {} };

As a side note, the main challenge is that when the client is loading, the UI doesn't have access to the server side (Angular security).

I also read that the best way to achieving this, is using the "environment/environments" files [Dev, Staging, Prod].

Final notes: the whole point of this is to have a centralized file to have all the configurations and make it easier to maintain.

Upvotes: 1

Views: 1701

Answers (1)

jfriend00
jfriend00

Reputation: 707148

For the client to dynamically get the socket.io config information from the server, you have to either include the config information in Javascript variables in a <script> tag in the HTML file that the client is running from OR you have to have a known URL that the client can send an Ajax call to request the socket.io config info.

The first could be part of a server-side template system that includes a script tag that defines a Javascript object containing socket.io config info in every page on the site so the socket.io config info is always available. That server-side template system could get the data from your one central place in the server.

The second could just set up an Ajax reachable route at a known URL that the client can fetch the config info as needed. This is probably slower than the first option because it involves a separate round-trip to the server, but is perhaps less of an imposition on the site architecture because it doesn't have to affection generation of HTML files on the site, it's just Javascript that goes with your socket.io initialization code. On the server, it's just an additional route to add that's independent of everything else.

Upvotes: 1

Related Questions