angularangular-routingangular-signalscanactivatecanactivatefn

How do I use Angular's inject within a canActivate function?


In the following canActivate function, I need to get the number of Items in a cart. I inject the CartService for this purpose but am getting an error that inject() must be called from an injection context. How do I fix this?

const cartService = inject(CartService);
const toastr = inject(ToastrService);

let numberOfCartItems = 0;

const cartEffect = effect(() => {
  numberOfCartItems = cartService.cartSignal().length;
})

export const canActivateCartGuard: CanActivateFn = (route, state) => {
  if(numberOfCartItems) {
    return true;
  }
  toastr.error("Your cart is currently empty!", "")
  return false;
};

Solution

  • You have the declare the services inside the canActivateFn since that has an injection context, also directly check the cart length and perform the boolean return.

    There is no state inside the canActivateFn the function is evaluated and everthing is destroyed. If you want to store some state, store it inside the service.

    export const canActivateCartGuard: CanActivateFn = (route, state) => {
      const cartService = inject(CartService);
      const toastr = inject(ToastrService);
      if(cartService.cartSignal().length) {
        return true;
      }
      toastr.error("Your cart is currently empty!", "")
      return false;
    };