0
votes

In my sample Angular 2 application , I am using ngrx/store to implement redux design pattern.

I have implemented CanActivate guard in my application and below is the related code

canActivate(route: ActivatedRouteSnapshot, router: RouterStateSnapshot): Observable<boolean> {

    this.store.dispatch(canActivate()); 
    // HOW TO RETURN value ??
}

And below are the relevant actions

export function canActivate(): Action {
$.blockUI();
return {
    type: UserActionTypes.CAN_ACTIVATE,
    payload:{}
  }
}

export function canActivateSuccess(canActivateResponse: any): Action {
$.unblockUI();
return {
    type: UserActionTypes.CAN_ACTIVATE_SUCCESS,
    payload: canActivateResponse.data
  }
}

And below is the relevant reducer code

....
case UserActionTypes.CAN_ACTIVATE_SUCCESS:           
        return Object.assign({}, action.payload);
.....

and below is the relevant effects code

 @Effect() canActivate$ = this.actions$
        .ofType(UserActionTypes.CAN_ACTIVATE)
       .switchMap(
       (action) => this.userService.canActivate()
           .map(response => canActivateSuccess)
        );

My question is , canActivate guard should return Observable of boolean , but whether to return true or false , will be known only within canActivateSuccess function/action , in that case how should I return a value from canActivate guard.

1

1 Answers

2
votes

You could return a $actions.ofType(..) in conjunction with take(1):

canActivate(route: ActivatedRouteSnapshot, router: RouterStateSnapshot): Observable<boolean> {
    this.store.dispatch(canActivate()); 
    return this.this.actions$
        .ofType(UserActionTypes.CAN_ACTIVATE_SUCCESS)
        .map(payloadToBoolean...);
}

Things to watch out for: For this solution you would have to ensure, that no other CAN_ACTIVATE_SUCCESS-action emits while this.userService.canActivate() is running. Otherwise this would potentially trigger the guard accidentally.