1
resposta

webSocket com java e angular

Segui este tutorial: https://www.stackextend.com/angular/websocket-with-spring-boot-and-angular/ Mas não funciona.

Vou colocar os códigos

WebSocketConfig

package br.com.ghnetsoft.comprasfood.cotacao.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/cotacao");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("ws").setAllowedOrigins("*").withSockJS();
    }
}

WebSocketResource

package br.com.ghnetsoft.comprasfood.cotacao.resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import br.com.ghnetsoft.comprasfood.cotacao.service.cotacaoitemfornecedorusuario.CotacaoItemFornecedorUsuarioService;

@RestController
public class WebSocketResource {

    @Autowired
    private CotacaoItemFornecedorUsuarioService service;
    @Autowired
    private SimpMessagingTemplate template;

    @GetMapping("buscar-qtd/")
    public Long buscarQuantidadeMensagens() {
        var contador = service.contadorCotacaoItemFornecedorUsuario();
        template.convertAndSend("/cotacao/qtd", contador);
        return contador;
    }
}

Angular

WsService.ts

import { Injectable } from '@angular/core';
import { Stomp } from '@stomp/stompjs';
import * as SockJs from 'sockjs-client';
@Injectable()
export class WebSocketService {
  public connect() {
    const socket = new SockJs('http://localhost:8500/modulo-cotacao-api/ws/');
    let stompClient = Stomp.over(socket);
    return stompClient;
  }
}

collapsable.component.ts

No ngOnInit() chamo o metodo this.webSocketServer();

webSocketServer(): void {
    let stompClient = this.webSocketService.connect();
    stompClient.connect({}, () => {
      stompClient.subscribe('/buscar-qtd/', (notifications: any) => {
        this.notifications = JSON.parse(notifications.body).count;
      });
    });
  }
1 resposta
O post foi fechado por inatividade. Para continuar o assunto, recomendamos criar um novo tópico. Bons Estudos!