【发布时间】:2021-03-31 04:41:33
【问题描述】:
我正在构建一个示例应用程序,在该应用程序中我正在执行 post api 调用。主要目标是使用 POST api 调用发送查询,该调用作为响应提供来自 api 的数据。这个 api 的主要特点是每 1 分钟(连续)提供更新的数据。
问题:主要问题是 api 显示特定时间实例的更新数据(例如:16:30 PM),但在一两分钟后查看更新数据(例如: 16:32 PM),我每次都必须刷新页面。我正在尝试使用 Web Socket 解决这个问题,以便在特定时间间隔后继续调用 api 并更新前端的数据,但不知何故它不起作用。
请找到以下代码供您参考。
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { io } from 'socket.io-client/build/index';
@Injectable({
providedIn: 'root'
})
export class SocketService {
socket: any;
readonly uri: string = 'https://apiurlexample.com/api/xxx/xxxxxx';
constructor(private http: HttpClient) {
debugger;
// this.socket = io(this.uri);
// this.socket = io.connect('http://localhost:8890', { query: "foo=bar" });
}
getMessages() {
debugger;
let observable = new Observable(observer => {
this.socket = io(this.uri);
this.socket.on('', (data: any) => {
observer.next(data);
});
return () => {
this.socket.disconnect();
};
})
return observable;
}
listen(eventName: string) {
debugger;
return new Observable((subscriber) => {
this.socket.on(eventName, (data: any) => {
subscriber.next(data);
})
});
}
emit(eventName: string, data: any) {
this.socket.emit(eventName, data);
}
getAllData(data: any) {
return this.http.post(`https://apiurlexample.com/api/xxx/xxxxxx`, data);
}
}
有什么解决办法吗?
【问题讨论】: