Search code examples
angularngrx

How to set a timer for an effect?


I have an effect that gets the number of active notifications from the user. But I need to get updated information on the number of active notifications every 5 minutes. And for this I added a timer. But I am getting the following error:

Type argument "Observable<({ title: string; description: string; } & TypedAction<"[Toastr Notification] display error">) | ({ count: number; } & TypedAction<"[Notifications] load count notifications success"> )>" cannot be assigned to a parameter of type "OperatorFunction<unknown, unknown>". Type "Observable<({ title: string; description: string; } & TypedAction<"[Toastr Notification] display error">) | ({ count: number; } & TypedAction<"[Notifications] load count notifications success">) >" does not provide a match for signature "(source: Observable): Observable".

How can this be fixed?

  loadCountNotifications$ = createEffect(() => {
    return this.actions$.pipe(
      ofType(loadCountNotifications),
      timer(0, 300000).pipe(
        switchMap(() => {
          return this.notificationsService
            .count()
            .pipe(
              map((data) => {
                return loadCountNotificationsSuccess({ count: data });
              }),
              catchError((err) => {
                return of(
                  displayError({
                    title: `${err.error.statusCode} ${err.error.error}`,
                    description: err.error.message,
                  })
                );
              })
            );
        })
      )
    );
  });

Solution

  • Use interval to poll for every 5 minutes.

    loadCountNotifications$ = createEffect(() => {
        return this.actions$.pipe(
            ofType(loadCountNotifications),
            switchMap(() =>
                interval(300000).pipe(
                    switchMap(() => {
                        return this.notificationsService.count().pipe(
                            map(data => {
                                return loadCountNotificationsSuccess({ count: data });
                            }),
                            catchError(err => {
                                return of(
                                    displayError({
                                        title: `${err.error.statusCode} ${err.error.error}`,
                                        description: err.error.message,
                                    })
                                );
                            })
                        );
                    })
                )
            )
        );
    });