1

como puedo extraer una data de mi bd en mysql y luego enviar ese objeto mediante web sockets estoy tratando de enviar notificaciones estoy haciendo una api restfull pero necesito enviar notificaciones en tiempo real cuando activen las notificaciones mediante mi api estoy llamando a un servicio en mi backend que deberia retornar el objeto con los datos de la bd pero cuando lo envio con el sockent.emit no llena nada una ayuda porfavor

estoy usando sequelize como orm para la bd

var express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server, {
  cors: {
      origin: "http://localhost:4200",
      methods: ["GET", "POST"],
      transports: ['websocket', 'polling'],
      credentials: true
  },
  allowEIO3: true
});
var notifications = require('./services/getNotifications').getNotifys();
  
io.on('connection',function(socket){
  const socketId = socket.id;
  console.log('se ha conectado el id: ' + '-----------' + socketId);
  //notification
  socket.emit('Notifications',notifications);
});
//rutas
module.exports = {server,io};

aqui es donde tengo mi conection y este es el servicio que llamo

var { Product_Notification,Product } = require('../models/index');

exports.getNotifys = async function(){

    const activeNotifications = await Product_Notification.findAll({
      where: { status:true }, 
      attributes:["id","value_to_report"],
      include:{
        association: "item",
        attributes:["id","name","product_quantity","product_code"],
        where:{active_notification: true}
      }
    }).catch(err =>{ return err});

    if(activeNotifications && activeNotifications.length > 0) return activeNotifications;
    else return message = "any notification active yet";
}

esto es lo que recibo en mi fron de angular introducir la descripción de la imagen aquí

y de esta manera es que conecto el socket con el front en angular

import { EventEmitter, Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';
@Injectable({
  providedIn: 'root'
})
export class NotifiSocketService extends Socket{
  outEven: EventEmitter<any> = new EventEmitter();
  callBack: EventEmitter<any> = new EventEmitter();
  constructor(
  ) {
    super({ url: 'http://localhost:5000', options: {}});
    this.listen();
  } 
  listen = () =>{
    this.ioSocket.on('Notifications',(res: any) => this.callBack.emit(res));
  }
  
}
servicio que llamo en mi componente navbar :

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit, DoCheck,OnDestroy, AfterViewInit {
  subscriptions:Subscription []=[];
  public notifications:Notification[] = [];
  public _notifications!:number
  public user:any;
  public msg:string = 'hola';
  public pinga:any;
  constructor(
    private socket: NotifiSocketService,
    private _userService:UserService,
    private _notificationService:NotificationService,
  ) {
    this.user = _userService.getIdentity();
    socket.callBack.subscribe( res =>{
      console.log(res);
    })
  }

agradeceria la ayuda soy bastante nuevo con sockets apenas lo estoy usando

si me pueden guiar de como hcaer el codigo mas escalable lo agradeceria

1 respuesta 1

2

No estas enviando nada en el emit de tu socket:

io.on('connection',function(socket){
  const socketId = socket.id;
  console.log('se ha conectado el id: ' + '-----------' + socketId);
  //Deberia ser un texto o un objeto.
  socket.emit('Notifications', "Una notificacion!!!");
});

Emitiendo eventos

io.on("connection", (socket) => {
  //Puede ser tu json...
  socket.emit("hello", "world");
});

// client-side
socket.on("hello", (arg) => {
  console.log(arg); // world
});

Edición

No debes mandar el callback, debes mandar el objeto:

socket.emit('Notifications',notifications);

Edicion 2 - Arreglos vacios son verdaderos

Esta es la validación que haces.

let arregloVacio = []


if(arregloVacio) alert('El arreglo no esta vacio')
else alert('El arreglo esta vacio')

Debes validar la longitud del arreglo:

let arregloVacio = []


if(arregloVacio.length) alert('El arreglo no esta vacio')
else alert('El arreglo esta vacio')

10
  • var notifications = require('./services/getNotifications').getNotifys(); esto envio esta mas arriba el 17 dic. 2021 a las 13:46
  • Estas enviando un callback en el emit. El emit no puede enviar callbacks, eso es para escuchar con on. Edito mi pregunta.
    – Legna
    el 17 dic. 2021 a las 16:33
  • es que ya lo hice tambien y solo devuelve el objeto vacio no se si es porque es un funcion asyncrona con sequelise o que pueda ser el 17 dic. 2021 a las 16:43
  • Y estas seguro que la consulta no esta devolviendo un valor vacio? La validación que haces dejaría pasar un arreglo vacío. Esta linea: if(activeNotifications) siempre será verdadero por que el query que haces con findAll, si no encuentra nada, devuelve un arreglo vacio.
    – Legna
    el 17 dic. 2021 a las 16:52
  • Agregue un ejemplo de lo comentado. Mira la segunda edición.
    – Legna
    el 17 dic. 2021 a las 16:56

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.