Angular正在使用socket.io创建许多套接字

时间:2018-11-22 10:24:49

标签: node.js angular socket.io

我编写了一个使用套接字连接的nodejs,有角度的客户端/服务器应用程序。当我进入主页或下一页时,它将创建一个套接字并正常工作,当我深入2层(路由)时,它将生成多个套接字。我正在使用命名空间,因为在每个页面中我都需要基于不同查询对象的不同套接字连接。

这是在有角度的应用程序中创建套接字客户端的代码

import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs/Observable';
import { Config } from '../config/env.config';
import { SocketConfig } from '../config/socket.config';   

@Injectable()
export class SocketService {

public host: string = Config.HOST;  

/**
 * * Creates a new SocketService
 */

initHomeSocket() {
    return io(this.host + SocketConfig.HOME);
}

initDashBoardSocket(dashboardId: string) {
    const query = 'dashboardId=' + dashboardId;
    return io(this.host + SocketConfig.DASHBOARD, 
this.setOptions(query));
}

 initDabaseSocket(dbId: string, queryId: string) {
    const query = 'queryId=' + queryId + SocketConfig.KEYJOIN + 
queryId;
    return io(this.host + SocketConfig.DATABASE, 
this.setOptions(query));        
}


 getSocketEmit(emitEvent: string, socket: SocketIOClient.Socket) {
    const observable = new Observable(observer => {
        socket.on(emitEvent, (data: any) => {
            observer.next(data);
        });
        return () => {
            socket.disconnect();
        };
    });
    return observable;
}

setOptions(queryString: string) {
    return { 'secure': SocketConfig.SECURE, 'reconnection': 
   SocketConfig.RECONNECT, 'reconnectionDelay': 
  SocketConfig.RECONNECT_DELAY, 'reconnectionDelayMax': 
  SocketConfig.RECONNECT_DELAYMAX, 'reconnectionAttempts': 
  SocketConfig.RECONNECT_ATTEMPTS, transport: SocketConfig.TRANSPORT, 
  query: queryString };
 }
}

0 个答案:

没有答案