Node.js 订阅不是一个函数/Socket.IO

Node.js 订阅不是一个函数/Socket.IO,node.js,angular,socket.io,Node.js,Angular,Socket.io,我正在编写一个聊天应用程序,我正在使用节点服务器和socket.io服务器端以及Angular和socket.io客户端。不幸的是,我在运行它时遇到了“this.socketService.getMessage(…).subscribe不是函数”错误。其他一切似乎都起作用了 app.component.ts: import { Component, OnInit, OnDestroy } from '@angular/core'; import { SocketService } from '.

我正在编写一个聊天应用程序,我正在使用节点服务器和socket.io服务器端以及Angular和socket.io客户端。不幸的是,我在运行它时遇到了“this.socketService.getMessage(…).subscribe不是函数”错误。其他一切似乎都起作用了

app.component.ts:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { SocketService } from './socket.service';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  title = 'chat';
  registered = false;
  username: string;

  constructor(public socketService: SocketService) {
  }

  ngOnInit(): void {
    this.socketService
      .getMessage()
      .subscribe(msg => {
        if (msg === 'Registered') {
          this.registered = true;
          console.log(this.registered)
        }
      });
  }

  register(username: string): void {
    console.log(username)
    this.username = username;
    this.socketService.sendMessage('register', username);
  }

  send(message: string): void {
    this.socketService.sendMessage('message', message);
  }


}
socket.service.ts:

import { Injectable } from '@angular/core';
import { io } from 'socket.io-client';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SocketService {

  socket;

  constructor() {
    this.socket = io('http://localhost:3000/');
  }

  getMessage(): Observable<any> {
    return this.socket.on('message', msg => {
      console.log(msg);
    });
  }

  sendMessage(type: string, words: any): void {
    console.log(type, words);
    this.socket.emit(type, words);
  }
}
从'@angular/core'导入{Injectable};
从“socket.io客户端”导入{io};
从“rxjs”导入{Observable};
@注射的({
providedIn:'根'
})
出口级SocketService{
插座
构造函数(){
this.socket=io('http://localhost:3000/');
}
getMessage():可观察{
返回此.socket.on('message',msg=>{
控制台日志(msg);
});
}
sendMessage(类型:字符串,单词:任意):void{
控制台日志(类型、文字);
this.socket.emit(类型,单词);
}
}

此.socket.on
不返回可观察对象,因此您不能像处理可观察对象那样
.subscribe()


它返回一个套接字,如文档中所述:

此.Socket.on
不返回可观察对象,因此您不能像处理可观察对象那样
.subscribe()


它返回一个Socket,如文档中所述:

let observable=new observable(observer=>{this.Socket=io(this.url);this.Socket.on('message',(data)=>{observer.next(data);});return()=>{this.Socket disconnect();})
这样做。因为socket.on是不可见的。您需要将其转换为可观察的。@GaurangDhorda,这是有效的。您想将其添加为答案吗?
let observable=new observable(observer=>{this.socket=io(this.url);this.socket.on('message',(data)=>{observer.next(data);});return()=>{this.socket.disconnect();};})
这样做。因为socket.on是不可见的。您需要将其转换为可观察的。@GaurangDhorda,这是有效的。是否要将其添加为答案?