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

Discussão em 'Angular' iniciado por koque, Novembro 27, 2024.

  1. koque

    koque Guest

    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;
    };

    Continue reading...

Compartilhe esta Página