dlam
dlam

Reputation: 145

Call api every x seconds not work with Ngrx + Angular

I want to update a list with every 10 seconds for example. I used operator 'timer' but the api not show in second times on Chrome -> Network tab.

My process: dispatch Load action - my api - method GET - only be called one time in Network tab. But if I created a button with function dispatch that action, my api will be called many times in Network tab/Chrome each time I click

My env: ngrx 7.4, rxjs 6.5.2, angular 7 So I don't know server auto block repeat calling api or if angular and ngrx is using cache

// My effect

  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.sstatic.net/tKgbE.png

Upvotes: 0

Views: 2664

Answers (1)

timdeschryver
timdeschryver

Reputation: 15487

You don't have to dispatch an action if you want to reload every x seconds, you can just use the timer stream:

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

More info at Start using ngrx/effects for this

Upvotes: 5

Related Questions