使用Socket.io在Angular 4应用中收听Websockets

时间:2019-02-26 10:45:42

标签: angular sockets websocket socket.io

我有一个Angular 4.x应用程序(客户端),在后端,我使用的是运行在localhost:4001上的NestJS应用程序(在express之上构建的框架)-我可以看到websocket已连接在网络> WebSockets标签下的Chrome DevTools中,出现以下响应。

42["update", {
"accountMessage": {
    "id": 478,
    "text": ""
},
"networksRequireResetting": [7, 8, 4, 9, 21, 49, 100000271, 100000311],
"_id": "5c7401ea28f6c221eca11ff3",
"accountId": 15,
"__v": 0
}]

我有一个套接字服务和另一个套接字通知服务-socket.service.ts和socket-notification.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import * as io from 'socket.io-client';
import { UserService } from "../user.service";
import { SocketNotificationService } from "./socket-notification.service";

@Injectable()
export class SocketsService {
public socketPort: number = 4001;
public serverPort: number = 3001;
private socket;
public url: string = 'http://localhost';

 constructor(
   private userService: UserService,
   private socketNotificationService: SocketNotificationService,
 ) {}

 public initSocket(): void {
   this.socket = io(this.url + ":" + this.socketPort, {
     transports: ['websocket'],
     query: {
       token: this.userService.getAuth().__token,
     },
     secure: true
 });

   this.socketNotificationService.init(this.socket); // 
}

public send(msg: any) {
  this.socket.emit('message', { message: msg } );
}

public onMessage() {
  return Observable.create(observer => {
    this.socket.on('message', msg => {
      observer.next(msg);
    });
 });
}

//套接字通知      从'@ angular / core'导入{可注射};

 @Injectable()
 export class SocketNotificationService {
 public socketConnection: any = {};
 public events: any = [];
 public notification: any = [];

 constructor() {

 }

 ngOnInit(): void {

 }

 public init(connection: object) {
   console.log(connection);
   this.socketConnection = connection;
 }

 public listenForEvent(eventName: string, successCallback: any) {

 }

 public disconnect() {
   if (this.socketConnection) {
     try {
      this.socketConnection.disconnect();
     } catch (e) {
      console.log('Error: ', e);
     }
    }
  }
}

在我的组件中,我具有以下功能-如何获取initIoConnection()以便从上面的websocket响应中识别json数据,以便在html模板中做一些附加的逻辑?

//在我的组件中

    ngOnInit() {
       this.initIoConnection();
    }

    public initIoConnection() {
       this.socketService.initSocket();

       // subscribe
       this.ioConnection = this.socketService.onMessage().subscribe(msg => {
         console.log('got a socket message'); // i never see this log??
       });
    }

我用console.log退出套接字实例,然后执行.send('some something here')执行套接字发出操作,但是onMessage处理程序似乎从未看到过-这是为什么的任何想法?

0 个答案:

没有答案