簡體   English   中英

如何在 TypeScript 中正確鍵入 RXJS WebSocket?

[英]How to properly type RXJS WebSocket in TypeScript?

我有一個小型服務器,我通過 WebSocket 與之通信,它向我發送一致的響應,我想正確輸入它。 所以我在 Angular 中使用 WebSockets,我的服務中有這個:

private socket$: WebSocketSubject<ResponseInterface>;
private createSocket$(): WebSocketSubject<ResponseInterface> {
  return webSocket({
      url: 'localhost:2343'
  });
}

然后我在做:

const toSend: PayloadInterface = {
  sendThis: true
};
this.socket$.next(toSend);

嗯,在這個階段,上面不會用 Typescript 編譯,因為我試圖將 PayloadInterface 對象傳遞到套接字中,套接字是用 ResponseInterface 輸入的。 我也有聽力:

public listen$(): Observable<ResponseInterface> {
   return this.socket$.asObservable();
}
  1. 我的問題是我不確定應該使用哪種類型/接口來聲明套接字本身。 應該是 ResponseInterface,因為我正在聽它,還是應該是 PayloadInterface,因為我想推送( next )到它?
  2. 然后,根據我在 1 中的選擇,我仍然會在聽它或“旁邊”它時遇到類型沖突。

我錯過了什么? any / unknown是不行的。

建議您在 Angular 應用程序中使用 socket.io-client 的類型定義。 然后定義一個服務如下:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import { Message } from '../model/message';
import { Event } from '../model/event';

import * as socketIo from 'socket.io-client';

const SERVER_URL = 'https://yourserverhost.com';

@Injectable()
export class SocketService {
    private socket;

    public initSocket(): void {
        this.socket = socketIo(SERVER_URL);
    }

    public send(message: Message): void {
        this.socket.emit('message', message);
    }

    public onEvent(event: Event): Observable<any> {
        return new Observable<Event>(observer => {
            this.socket.on(event, () => observer.next());
        });
    }
}

定義一個事件枚舉:

export enum Event {
    CONNECT = 'connect',
    DISCONNECT = 'disconnect'
}
Then subscribe to your service functions from your Angular component:

export class ChatComponent implements OnInit {
  constructor(private socketService: SocketService) { }

   ngOnInit(): void {
    this.initIoConnection();
  }

  private initIoConnection(): void {
    this.socketService.initSocket();

    this.ioConnection = this.socketService.onMessage()
      .subscribe((message: Message) => {
        this.messages.push(message);
      });


    this.socketService.onEvent(Event.CONNECT)
      .subscribe(() => {
        console.log('Connected to the server');
      });

    this.socketService.onEvent(Event.DISCONNECT)
      .subscribe(() => {
        console.log('Disconnected');
      });
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM