KevinTale
KevinTale

Reputation: 1858

Wait for resource to load in guard using ngrx and selectors

TLDR: I've got a isLoading selector, I want to use that in my guard to active the route only when this selector is false.

Here is the reducer :


export const initialState: State = {
  loaded: false,
  loading: false,
  success: {
    [...]
  }
};


export const reducer = createReducer(
  initialState,

  on(
    fromApiActions.loadRequest,
    (state): State => ({
      ...state,
      loading: true
    })
  ),

  on(
    fromApiActions.loadRequestSuccess
    (state, partialState): State => ({
      ...state,
      loaded: true,
      loading: false,
      success: {
        ...state.success,
        ...partialState
      }
    })
  ),

  on(
    fromApiActions.loadRequestFail,
    (state): State => ({
      ...state,
      loaded: false,
      loading: false
    })
  )
);


And I've got a selector that select loading from state. When bootstrapping the app, I'm dispatching the LoadRequest action which turns loading to true.

Here is my guard :

export class CanActivateChildrenGuard implements CanActivateChild {
  constructor(private store: Store<fromDataUserInformations.State>) {}

  canActivateChild(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {

    return this.store.pipe(
      select(fromDataUserInformations.isLoading),
      // what to use here?
    );

  }

}

I cannot manage to make the guard wait for the LoadRequestSuccess to execute (which is in the LoadRequest effect) in order to turn loading to false so I can return something like !loading I guess.

Thanks!

Upvotes: 2

Views: 2104

Answers (1)

satanTime
satanTime

Reputation: 13539

return this.store.pipe(
      select(fromDataUserInformations.isLoading),
      skipWhile(flag => !flag),
      skipWhile(flag => flag),
      mapTo(true),
    );

it waits until fromDataUserInformations.isLoading is true, then it waits until fromDataUserInformations.isLoading is false again, then it releases the guard with true (means allows navigation).

Upvotes: 9

Related Questions