Search code examples
angularngrxrefresh-token

I need to create effect which will in time intervals refresh access token with refresh-token


I want to create effect which will refresh token in time intervals after user's successful login i also need to select refreshToken from store and it is starting to be too much complicated for me and i can't figure it out how to do it.

Effect so far

  @Effect()
  refreshAccessToken$ =
    this.actions$.pipe(
      ofType(AccountActionsTypes.AccountLoginSuccess),
      map(() => {
        interval(5000)
          .pipe(
            mapTo(() => this.store
              .pipe(
                select(selectRefreshToken),
                map(refreshToken => {
                  if (refreshToken != '' && refreshToken != undefined) {
                    this.accountService.refreshToken(refreshToken)
                      .pipe(
                        map((response: { token: string }) => {
                          return {type: AccountActionsTypes.RefreshTokenSuccess, token: response.token};
                        })
                      );
                  } else {
                    return {type: AccountActionsTypes.RefreshTokenSuccess, token: ''};
                  }
                })
              )));
      }));

But i get this error enter image description here

Maybe somebody can find this helpful, this is an effect fixed by advice:

@Effect()
  refreshAccessToken$ =
    this.actions$.pipe(
      ofType(AccountActionsTypes.AccountLoginSuccess),
      switchMap(() => {
        return interval(5000)
          .pipe(
            switchMap(() => this.store
              .pipe(
                select(selectRefreshToken),
                switchMap((refreshToken) => this.accountService.refreshToken(refreshToken)
                  .pipe(
                    map((response: { token: string, status: string }) => {
                      if (response.token !== undefined) {
                        return {
                          type: AccountActionsTypes.RefreshTokenSuccess,
                          token: response.token,
                        };
                      } else {
                        return {type: AccountActionsTypes.RefreshTokenWrong, status: response.status};
                      }
                    })
                  ))
              )));
      }));

Solution

  • You have to use a flattening operator if you want to return an inner observable:

     @Effect()
      refreshAccessToken$ =
        this.actions$.pipe(
          ofType(AccountActionsTypes.AccountLoginSuccess),
          // 👇👇👇
          switchMap(() => { ... })