【问题标题】:Binding real time data without reloading the page in Angular绑定实时数据而无需在 Angular 中重新加载页面
【发布时间】:2020-06-20 17:28:59
【问题描述】:

我有一个发送实时数据的 API,我想在我的视图中显示数据而不刷新页面。 setInterval 在我的情况下不起作用,因为 API 的响应时间可能会延迟,我不想重新加载组件。

有什么解决办法吗:

ngOnInit(){
  this.realTimeData()
}

realTimeData(){
  this.http.get(api)
    .subscribe(res => {
       this.bindData = res;
    })
}

【问题讨论】:

  • 你的api如何发送实时数据?据我所知,您需要套接字或 RPC。收到数据后,http observables 变冷了,所以我认为您需要使用 rxjs 多播运营商之一来保持它的热度
  • @ihorbond 我会检查多播运营商。不知道这个

标签: angular typescript


【解决方案1】:

你可以使用 rxjs 的区间可观察操作符。 这是一个小例子:

import 'rxjs/add/observable/interval';
... 
sub = Observable.interval(10000)
    .subscribe((val) => { <your code here> });

您也可以通过以下方式阻止它取消订阅:

this.sub.unsubscribe();

或使用timerObservable

timer = Observable.timer(10000);
this.timer.subscribe((t) => this.<your method>());

【讨论】:

  • setInterval有什么区别?有时我的 api 调用需要 2 分钟才能获取数据
【解决方案2】:

按间隔轮询http 端点:

您可以使用 timerinterval rxjs 创建运算符来发出和触发 API 调用。

  realTimeDataSubscription$: Subscription;

  ngOnInit() {
    this.realTimeData();
  }

  realTimeData() {
    this.realTimeDataSubscription$ = timer(0, 1000)
      .pipe(switchMap(_ => this.http.get(api)))
      .subscribe(res => {
        this.bindData = res;
      });
  }

  ngOnDestroy() {
    this.realTimeDataSubscription$.unsubscribe();
  }

始终建议将http 调用放在服务文件中并注入到组件中。

【讨论】:

  • 为什么我们在这里使用pipeswitchMap?你能解释一下吗?
  • switchMap 这里用于取消所有以前的呼叫,如果它们花费超过 1000 毫秒并进行新呼叫。如果您的 API 调用需要更多时间,那么最好使用的运算符是 exhaustMapexhaustMap 在旧的 API 调用解决之前不会进行新的 API 调用
猜你喜欢
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-03
  • 2019-07-10
  • 1970-01-01
  • 2016-01-12
  • 2021-01-10
相关资源
最近更新 更多