使用websocket实时更新Angular应用数据

时间:2018-06-20 06:35:21

标签: spring angular angular5 sockjs

我在服务器端用Spring编写了API,并且还管理了Websocket代码,该代码打开套接字并不断响应某些数据(例如select school, rating, case when rownum = 1 then 'i-' || name when rownum = 2 then 'ii-' || name when rownum = 3 then 'iii-' || name when rownum = 4 then 'iv-' || name when rownum = 5 then 'v-' || name end Name from mytable where school = 'SchoolN'; 返回点赞次数)。

我该如何在服务中调用此API,以不断检查更新的值(我不想在服务调用中使用任何时间间隔)?

2 个答案:

答案 0 :(得分:2)

您可以使用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

中找到有关此内容的完整教程

答案 1 :(得分:1)