【问题标题】:Call api every x seconds not work with Ngrx + Angular每 x 秒调用一次 api 不适用于 Ngrx + Angular
【发布时间】:2020-02-29 16:52:08
【问题描述】:

例如,我想每 10 秒更新一次列表。我使用了运营商“计时器”,但 api 没有在 Chrome -> 网络选项卡上第二次显示。

我的流程:调度加载操作 - 我的 api - 方法 GET - 仅在网络选项卡中调用一次。 但是,如果我创建了一个具有功能调度该操作的按钮,则每次单击时,我的 api 都会在网络选项卡/Chrome 中被多次调用

我的环境:ngrx 7.4,rxjs 6.5.2,角度 7 所以我不知道服务器自动阻止重复调用 api 或者 angular 和 ngrx 是否正在使用缓存

//我的效果

  load$: Observable<Action> = this.action$.pipe(
    ofType<Load>(NotificationActionTypes.load),
    switchMap(() => timer(0, 10000)),
    switchMap((action) => {
      return this.notiService.getNotifications().pipe(map((res: any) => {
        return new LoadSuccess({
          result: res,
        });
      }));
    })
  );```

[![enter image description here][1]][1]
See my image, 20/125 request, 125 continue increasing, 20/130, 20/145, but number 20 didn't increase


  [1]: https://i.stack.imgur.com/tKgbE.png

【问题讨论】:

  • 你想发送NotificationActionTypes.load,还是应该每10秒调用一次api?
  • @timdeschryver 因为我将通知列表保存在 ngrx 存储中并从中显示列表,在调度加载操作后,我将调度 LoadSuccess 以保存数据。我的意思是我想每 10 秒调用一次 api 来获取最新列表。 blog.thoughtram.io/angular/2018/03/05/… 好像是这样的,但它没有ngrx,所以我应用了它但没有用

标签: angular timer rxjs ngrx polling


【解决方案1】:

如果你想每 x 秒重新加载一次,你不必调度一个动作,你可以使用 timer 流:

@Effect()
ping = interval(10000).pipe(
  switchMap((action) => {
    return this.notiService.getNotifications().pipe(map((res: any) => {
      return new LoadSuccess({
        result: res,
      });
    }));
}));

更多信息Start using ngrx/effects for this

【讨论】:

  • 嗨@timdeschryver,我以前什至不知道。但是在应用上面的代码之后,请求仍然是第一次触发。似乎 Chrome 正在阻止计时器,它显示一个警告“[Violation] 'setInterval' 处理程序花费了 70 毫秒”。如果使用旧方法,当页面加载完成时,没有动作调度。我单击一个按钮来调度加载操作,它奇怪地每 10 秒正确调用一次 api。我不知道为什么
  • 等待...“请求仍然第一次触发”您不想第一次触发它吗?
  • 我希望每 10 秒调用一次 api。但只开火第一次,不是第二次。当看到记录器时,动作仍然每 10 秒发送一次,但 api 不会从第二次调用;)
  • 我通过在调用 api GET 时添加随机参数来修复它
猜你喜欢
  • 1970-01-01
  • 2012-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-27
  • 2019-02-01
  • 1970-01-01
相关资源
最近更新 更多