Socket-io dynamic initialization

时间:2019-01-09 21:50:45

标签: node.js typescript socket.io angular5

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.

1 个答案:

答案 0 :(得分:1)

要使客户端从服务器动态获取socket.io配置信息,您必须将Java变量中的配置信息包含在客户端从其运行的HTML文件的<script>标签中,或者必须具有一个已知的URL,客户端可以发送一个Ajax调用来请求socket.io配置信息。

第一个可能是服务器端模板系统的一部分,该系统包含一个脚本标签,该脚本标签定义站点上每个页面中包含socket.io配置信息的Javascript对象,因此socket.io配置信息始终可用。该服务器端模板系统可以从服务器中的一个中心位置获取数据。

第二个可能只是在已知URL上设置Ajax可达路由,客户端可以根据需要获取配置信息。这可能比第一种选择要慢,因为它涉及到服务器的单独往返,但是对站点体系结构的影响较小,因为它不必影响站点上HTML文件的生成,而只是Javascript这与您的socket.io初始化代码一起使用。在服务器上,这只是添加的另一条途径,而与其他所有事物无关。