简体   繁体   English

如何在 Angular 中实时异步地从 REST API 获取数据

[英]How to get data from a rest API asynchronously in realtime in Angular

In my component file i use the http client to get an observable of the json file from an api endpoint:在我的组件文件中,我使用 http 客户端从 api 端点获取 json 文件的 observable:

this.data =  this.http.get(api);

in the template i am binding the data field using the async pipe:在模板中,我使用异步管道绑定数据字段:

<td *ngFor="let post of (data | async)"> {{post.title}} </td>

Now i am getting the data, the problem is that i want it to happen in realtime without having to refresh the page.现在我正在获取数据,问题是我希望它实时发生而不必刷新页面。 So is there anyway i can achieve asynchronous data loading那么无论如何我可以实现异步数据加载

PS聚苯乙烯
I have already tried some workarounds like setting interval to continuously subscribe to the observable but that would just deplete resources and it seems like there's another cleaner way that i am missing.我已经尝试了一些变通方法,例如设置时间间隔以连续订阅可观察对象,但这只会耗尽资源,而且似乎还有另一种更清洁的方法我错过了。

You can't do anything at front side for making it real time.你不能在前端做任何事情来使它实时。 Async pipe will keep eye on response but in order to get response you must have to hit API after some Time interval or something similar.异步管道将密切关注响应,但为了获得响应,您必须在某个时间间隔或类似的时间后点击 API。 As you already said it's not cleaner solution.正如您已经说过的,这不是更清洁的解决方案。 You can achieve this using web socket which is back end thing.您可以使用后端的 web socket 来实现这一点。 Some of databases are real time in nature by default.默认情况下,某些数据库本质上是实时的。 Firebase is one of them. Firebase 就是其中之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM