【问题标题】:Angular change Socket.io url on runtimeAngular 在运行时更改 Socket.io url
【发布时间】:2020-06-26 08:32:51
【问题描述】:

我的app.module.ts 是这样的:

// 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 {}

希望能够更改config.url 的值。但我不知道该怎么做,因为在初始化后更改config.url 值不会在SocketIoModule.forRoot(config) 上更改它。

【问题讨论】:

    标签: angular typescript socket.io


    【解决方案1】:

    就像@03c7c0ace395d80182db07ae2c30f0 说的那样。

    解决方案: app.module.ts 中的配置就像

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

    并提供服务来处理 URL 更改(在此代码中仅端口更改但应该相同):

    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);
      }
    }
    

    【讨论】:

    • 对于任何尝试这种方法的人,只要记住在将库导入模块时禁用 autoConnect 以避免它创建默认套接字:SocketIoModule.forRoot({url:'',options:{autoConnect:false}})
    【解决方案2】:

    您可以尝试使用

    断开连接
    this.socket.disconnect()
    

    然后用

    创建一个新实例
    this.socket = io("http://foo")
    

    这个库只是 socketio-client 的一个包装器

    【讨论】:

      猜你喜欢
      • 2018-04-27
      • 2018-03-04
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 2018-03-30
      相关资源
      最近更新 更多