如何使用websocket发送消息

时间:2017-09-14 09:10:17

标签: node.js angular typescript websocket socket.io

我试图将WebSocket中的消息发送到TypeScript。我创建了一个带有两个函数的Socket服务:.onMessage()和.emit(message):

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

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

const SERVER_URL = 'http://localhost:8080';

@Injectable()
export class SocketService {
  private socket;

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

  public send(message?: Message): void {
    this.socket.emit('displayHello', { to: 'flo@NXS_DEV_FLO2', from: 'flo@NXS_DEV_FLO2', name: 'displayHello'})
  }

  public onMessage(): Observable<any> {
    return new Observable(observer => {
      this.socket.on('message', (data) => {
        observer.next(data);
      });
    });
  }
}

我的.onMessage函数不显示任何错误。我的.emit(消息)函数将此显示为错误:

ERROR TypeError: Cannot read property 'emit' of undefined

应该怎么做?

/////////////// EDIT ///////////////////

我将这些功能称为:

addNewMessage(newMessage: Message): void {
    this.socketService.initSocket();
    this.socketService.onMessage();
    this.socketService.send(newMessage);
}

/////////////编辑2 ////////////////////

当我在我的控制台中测试它时,它可以工作:

public onMessage(): Observable<any> {
return new Observable(observer => {

  this.socket.on('displayHello', function(data) {
    $.pnotify({
      title: 'Hello',
      text:  data.from + ' te dis bonjour ' + data.to,
      type:  'info'
    });
  });
}

但是当我尝试输入代码时出现此错误:

Property 'pnotify' does not exist on type '(search: string) => ElementFinder'

0 个答案:

没有答案