简体   繁体   中英

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!

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM