【问题标题】:Refreshing data in service刷新服务中的数据
【发布时间】:2018-07-23 19:52:42
【问题描述】:

API 中的数据不断变化。在 Angular 中刷新数据的最佳方法是什么? bitfinex.com API

我有一个服务和组件。在服务中,我使用“get”下载数据。

服务:

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 秒后显示数据。

【问题讨论】:

  • 您可以在后端和前端使用 Web 套接字吗?因为对于这个应用程序来说,它们可能比长轮询更好。

标签: angular rxjs6


【解决方案1】:
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')),
);

问题出在这段代码中。 interval(5000) 将在前 5 秒后每 5 秒发射一次。这是您观察到的行为。 您可以使用timer(0,5000) 来获得一个以 1 次发射开始,然后每 5 秒重复一次的 observable。

另外,我不确定distinctUntilChanged() 应该在这里做什么。 interval(5000) 将每 5 秒发出一个递增的数字,因此该值将始终是唯一的。

switchMap 后面似乎还有一个多余的逗号,您不需要。

【讨论】:

    【解决方案2】:

    我已尝试在 this stackblitz 中重现您的问题,但我做不到。

    你能试试这个并告诉我它有什么问题吗(除了服务器端的 CORS,你无能为力)

    您的问题可能与此有关:

    根据他们的政策,您不能每 5 秒轮询一次 API(您正在对他们进行 DDOS 攻击:P)。您每分钟可以处理约 10 个请求。

    试试他们的websocket api,它会在数据发生变化时将数据流式传输给您,而无需从客户端轮询(服务器会在新数据可用时向您发送新数据,您只需要处理它)。

    【讨论】:

    • 除了服务器端的 CORS,你无能为力老实说,这更多地依赖于客户端而不是服务器。
    【解决方案3】:

    1) 如果您不在重定向/页面离开时销毁事件监听器,这将在后台运行。

    我建议实现一个析构函数。

    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 中添加你的事件监听器

    this.eventListeners.push(this.$scope.$on("$destroy", this.deregisterListeners.bind(this)));
    this.intervalFunc = setInterval(() => {
         // your code / function that calls the data here
     });
    

    【讨论】:

      【解决方案4】:

      当您设置每 3 秒刷新一次时,它们会阻塞。 5 秒最佳,经过测试:D

      首先,我想在没有 websockets 的情况下学习,因此我的问题是如何做到最好。

      【讨论】:

      • 答案并不意味着为您的问题添加信息。您应该编辑原始问题或添加评论。您可能还不能发表评论,因此您应该编辑 OP。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多