1

我需要在 Angular 中实现一个 socket.io 客户端,然后我找到了 ngx-socket-io。它似乎工作正常,但我没有找到在启动连接时发送凭据的选项,如官方页面所述,使用 auth > token。(https://socket.io/docs/v4/middlewares/#Sending-credentials

我已经实现了服务器并以这种格式工作,从socket.handshake.auth.token.

如何通过 ngx-socket-io 发送此令牌?
我可以在角度中使用任何其他 socket.io 库吗?

4

2 回答 2

1

I found a workaround, inserting empty options in the constructor and adding authentication right after. It's not ideal, but it seems to work normally. I'm sharing it here in case anyone else needs it.

import { AuthService } from '@my/core';
import { Socket } from 'ngx-socket-io';
import { environment } from 'src/environments/environment';

export class MySocket extends Socket {
    constructor(
        private authService: AuthService,
    ) {
        super({ url: environment.urlSocket, options: {} });
        this.ioSocket['auth'] = { token: this.authService.token };
    }
}
于 2021-09-17T21:23:22.537 回答
0

您可以创建可用于启动 Socket 连接的 Injectable 服务

import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';
import { AuthenticationService } from '@app/auth/services/authentication.service';

@Injectable({
  providedIn: 'root'
})
export class WebSocketService {
  constructor(private socket: Socket, private authenticationService: AuthenticationService) {
    const currentUser = this.authenticationService.currentUserValue;
    this.socket.ioSocket.io.opts.query = { Authorization: `${currentUser.accessToken}` };
  }

  public sendMessage(event, message) {
    this.socket.emit(event, message);
  }

  public getMessage(eventName) {
    return new Observable(observer => {
      this.socket.on(eventName, message => {
        observer.next(message);
      });
    });
  }
}

在您的组件中,您可以注入您的服务:

import { WebSocketService } from './web-socket.service';

@Component({
  selector: 'app-conversation',
  templateUrl: './conversation.component.html',
  styleUrls: ['./conversation.component.scss']
})
export class MyComponent implements OnInit {
  constructor( private webSocket: WebSocketService) {}
  
  ngOnInit() {
    this.webSocket.getMessage('testing').subscribe(msg => console.log(msg));
   }
}

在您的服务器中,收到令牌

handleConnection(socket: Socket) {
const token  = socket.handshake.query.Authorization;
于 2021-09-16T20:46:32.343 回答