Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading