【问题标题】:Update Angular app data in real time using websocket使用 websocket 实时更新 Angular 应用数据
【发布时间】:2018-06-20 06:35:21
【问题描述】:

我在服务器端使用 Spring 编写的 API 还管理 websocket 代码,该代码打开套接字并不断响应一些数据(例如 /getlikes 返回点赞数)。

如何在持续检查更新值的服务中调用此 API(我不想使用任何时间间隔进行服务调用)?

【问题讨论】:

  • 一旦客户端订阅了 websocket 端点,只需随时从服务器发送您的消息,所有订阅的客户端都会收到消息。

标签: spring angular angular5 sockjs


【解决方案1】:

你可以使用sockjs-client 做一些这样的事情。

import { Component } from '@angular/core';
import * as Stomp from 'stompjs';
import * as SockJS from 'sockjs-client';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private serverUrl = 'http://localhost:8080/socket'
  private title = 'WebSockets chat';
  private stompClient;

  constructor(){
    this.initializeWebSocketConnection();
  }

  public initializeWebSocketConnection(){
    let ws = new SockJS(this.serverUrl);
    this.stompClient = Stomp.over(ws);
    let that = this;
    this.stompClient.connect({}, function(frame) {
      that.stompClient.subscribe("/chat", (message) => {
        if(message.body) {
          $(".chat").append("<div class='message'>"+message.body+"</div>")
          console.log(message.body);
        }
      });
    });
  }

  public sendMessage(message){
    this.stompClient.send("/app/send/message" , {}, message);
    $('#input').val('');
  }

}

您可以在 article 中找到完整的教程

【讨论】:

  • @anirudha hie 感谢您的回复,我使用的是 spring 服务器(不是节点 js)我们可以这样做 SockJs 和 StompJS
  • 你可以使用sockjs-client-for-angular
  • 感谢我关注了 sockjs 和 stompjs 的文档,您能否添加一些演示,演示如何在 ui 上使用该 api 更新结果从服务文件和 component.ts 调用 api。
  • 我更新了答案。浏览我分享的链接。
  • 嗨@anirudha我会经历这个,你能告诉我:我需要实时更新我的​​仪表板值,在他的情况下,我只需要订阅这个回复我的频道(/chat)数据,我这里一团糟,你能帮忙吗
【解决方案2】:

【讨论】:

  • 谢谢。我需要在 SockJS 和 Stompjs 的帮助下完成这项工作,因为我的服务器在 Spring 中,建议使用 Sockjs 和 Stompjs
猜你喜欢
  • 2012-10-08
  • 1970-01-01
  • 2023-03-16
  • 2017-09-13
  • 1970-01-01
  • 2014-09-19
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
相关资源
最近更新 更多