您可以创建可用于启动 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;