【问题标题】:post api call using websocket in Angular not working在Angular中使用websocket发布api调用不起作用
【发布时间】: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);
}
}

有什么解决办法吗?

【问题讨论】:

    标签: angular websocket


    【解决方案1】:

    你所做的是正确的。但是,你只在前端设置了websocket,你有没有从后端连续广播? 我的意思是你的套接字已经准备好监听来自后端的变化,但是后端会在一两分钟后发送任何东西吗?

    编辑:

    或者你可以暗示只添加一个间隔:

    setInterval(() => {
        getData(); 
    }, 60000)
    

    【讨论】:

    • Quyen Huynh:是的,后端每分钟都会发送更新的数据。但要在前端反映这一点,我必须在一分钟后手动刷新页面。
    • 您能否尝试 console.log 一些内容以确保它在后端工作?或者你可以使用setInterval
    猜你喜欢
    • 1970-01-01
    • 2019-03-21
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多