简体   繁体   English

如何在发射成功时处理从 service.ts 到 component.ts 的 socket.io 确认 Angular 8

[英]How to handle socket.io acknowledgement from service.ts to component.ts on emit success Angular 8

When the client emits a new message to the server using socket.io, the server sends an acknowledgment of the newly created messageId with the callback fn().当客户端使用 socket.io 向服务器发送新消息时,服务器会通过回调 fn() 发送对新创建的 messageId 的确认。 I am able to log the messageId in the service.ts, but cannot figure out a way to "get" the messageId to the component.ts (in order to update the newly created message with an ID).我能够在 service.ts 中记录 messageId,但无法找到将 messageId“获取”到 component.ts 的方法(以便使用 ID 更新新创建的消息)。 with the way the code is set below, I get an angular error saying I cannot subscribe to this.appService.newMessage(), even though I am returning an Observable of the new message id with of(newMsgId) in service.ts.通过下面设置代码的方式,我得到一个 angular 错误,说我无法订阅 this.appService.newMessage(),即使我在 service.ts 中返回一个带有 of(newMsgId) 的新消息 ID 的 Observable。 Pls lmk if I can add any more information to help如果我可以添加更多信息来帮助,请 lmk

server.js
--------

socket.on('newStaffMessage', function (data, fn) {
    var msg = new Message({
      sender: data.senderId,
      content: { text: data.content.text, attachment: null },
      dateTime: new Date(),
    });

    msg.save((err, messageDoc) => {
      Conversation.findByIdAndUpdate(
        { _id: data.conversationId },
        {
          $push: { messages: messageDoc._id },
        },
        { new: true },
        function (err, convoDoc) {
          if (!err) {
            User.findById(data.senderId, function (err, userDoc) {
              const payload = {
                conversationId: convoDoc._id,
                _id: messageDoc._id,
                content: {
                  text: msg.content.text,
                  attachment: msg.content.attachment,
                },
                dateTime: msg.dateTime,
                sender: {
                  _id: userDoc._id,
                  firstName: userDoc.firstName,
                  lastNameInitial: userDoc.lastNameInitial,
                },
              };

              io.in(convoDoc._id).emit('newStaffMessage', payload);
              fn({messageId: messageDoc._id});
            });
          } else {
            console.log(err);
          }
        }
      );
    });
  });
service.ts
----------

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Observer, of } from 'rxjs';
import * as io from 'socket.io-client';

@Injectable({
  providedIn: 'root',
})
export class AppService {
  private socket = io('http://localhost:3000');

  constructor(private http: HttpClient) {}

  newMessage(msg) {
    this.socket.emit('newStaffMessage', msg, (newMsgId) => {
      return of(newMsgId);
    });
  }
component.ts
------------
this.appService.newMessage(newMessage).subscribe(data => {
      console.log(data);
    })

You should properly convert handling socket.io event with callback to Observable .您应该正确地将处理 socket.io 事件与回调转换为Observable

I'd suggest you two options here:我建议你在这里有两个选择:

1) Leverage Observable constructor or create operator with given subscription function: 1)利用给定订阅 function 的Observable构造函数或create运算符:

import { Observable } from 'rxjs';
...
newMessage(msg) {
  return Observable.create(observer => {
    this.socket.emit('newStaffMessage', msg, (newMsgId) => {
      observer.next(newMsgId);
    });
  });
}

2) Use dedicated for such purposes RxJS bindCallback function: 2) 专用于此类用途 RxJS bindCallback function:

import { bindCallback } from 'rxjs';

newMessage(msg) {
  return bindCallback(this.socket.emit)('newStaffMessage', msg);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何正确地将函数从 component.ts 移动到服务文件? - How to properly move function from component.ts to a service file? 如何在 Angular (component.ts) 中使用 JS function - How to use JS function in Angular (component.ts) Collapsible Sidebar 如何在angular component.ts文件中访问JS文件api - How to access JS file api in angular component.ts file Angular - 当它们在 component.ts 文件中启动时,如何从指令内部检测表单事件? - Angular - How do I detect form events from inside a directive when they are initiated in component.ts file? 如何将变量从一个函数传递到同一component.ts中的另一个函数 - how to pass variable from one function to another function in same component.ts in angular 6 如何在component.ts中将数据从一个函数传递到另一个函数,angular2 - how to pass data from one function to another in component.ts , angular2 如何将index.html页面中的值传递给angular4中的component.ts文件 - How to pass a value from index.html page to component.ts file in angular 4 如何将角度从component.ts传递给html SVG - How to pass a class name in angular from component.ts to html SVG 存储来自 service.ts 的数据以在同一个 service.ts 中使用 - storing data from service.ts to use in the same service.ts 来自component.ts的* ngFor访问元素 - Access element of *ngFor from component.ts
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM