Angular 正在刷新服务中的数据
API中的数据不断变化。在Angular中刷新数据的最佳方式是什么 我有一个服务和组件。在服务中,我使用“get”下载数据 服务:Angular 正在刷新服务中的数据,angular,rxjs6,Angular,Rxjs6,API中的数据不断变化。在Angular中刷新数据的最佳方式是什么 我有一个服务和组件。在服务中,我使用“get”下载数据 服务: getPrice(){ return this.http.get('xxx'); } ngOnInit() { this.getPrices(); setInterval(() => { this.getPrices(); }, 5000); } getPrices(){ this.tick.
getPrice(){
return this.http.get('xxx');
}
ngOnInit() {
this.getPrices();
setInterval(() => {
this.getPrices();
}, 5000);
}
getPrices(){
this.tick.getPrice().subscribe(prices => {
console.log(prices);
});
}
组件:
getPrice(){
return this.http.get('xxx');
}
ngOnInit() {
this.getPrices();
setInterval(() => {
this.getPrices();
}, 5000);
}
getPrices(){
this.tick.getPrice().subscribe(prices => {
console.log(prices);
});
}
正如您在组件中看到的,我使用“setInterval”并每5秒刷新一次
我试图直接在服务中刷新数据
return interval(5000).pipe(
// ignore new term if same as previous term
distinctUntilChanged(),
// switch to new search observable each time the term changes
switchMap(() => this.http.get('xxx')),
);
但它仅在5秒后显示数据。我已尝试在中重新创建您的问题,但无法 你能试试这个并告诉我它有什么问题吗(除了CORS,它是服务器端,你不能做任何事情) 您的问题可能与此有关: 根据他们的策略,您不能每5秒轮询一次API(您使用的是:p)。您每分钟可以处理约10个请求 尝试他们的方法,在数据更改时将数据流传输给您,而无需从客户端进行轮询(服务器将在数据可用时向您发送新数据,您只需处理即可)。1)如果您在重定向/页面离开时不销毁eventlisteners,则此操作将在后台运行 我建议实现一个析构函数
deregisterListeners() {
this.eventListeners.forEach(listener => {
listener();
});
_.remove(this.eventListeners); //this is lodash, it loops through all instances of w/e you're looping through
clearInterval(this.intervalFunc);
}
然后在ngOnInit中添加这样的EventListener
this.eventListeners.push(this.$scope.$on("$destroy", this.deregisterListeners.bind(this)));
this.intervalFunc = setInterval(() => {
// your code / function that calls the data here
});
当您设置每3秒刷新一次时,它们会阻塞。5秒为最佳,测试:D 首先,我想在没有WebSocket的情况下学习,因此我的问题是如何做到最好
return interval(5000).pipe(
// ignore new term if same as previous term
distinctUntilChanged(),
// switch to new search observable each time the term changes
switchMap(() => this.http.get('xxx')),
);
问题出在这段代码中<代码>间隔(5000)在前5秒之后,仅每5秒发射一次。这就是你观察到的行为。
您可以使用定时器(05000)
获取一个从1发射开始,然后每5秒重复的可观测值
另外,我不确定distinctUntilChanged()
在这里应该做什么<代码>间隔(5000)将每5秒发出一个递增的数字,因此该值始终是唯一的
在
开关映射之后似乎还有一个多余的逗号,您不需要。您可以在后端和前端使用web套接字吗?因为对于这个应用程序来说,它们可能比长时间轮询要好。除了服务器端的CORS之外,老实说,CORS比服务器端更依赖于客户机。答案并不意味着为您的问题添加信息。您应该编辑原始问题或添加注释。您可能还不能评论,因此应该编辑OP。