Search code examples
angularspartacus-storefront

Spartacus add to cart


With Spartacus I have been able to change the PDP call to take an extra parameter which is the store code and its working fine. But when I add the product to the cart the api call fails because the store code is not being passed through.

I have started by extending the active-cart and multi-cart services to take my extra parameter and I am struggling with one of the private variables that are used in the function that are not exposed.

Am I on the right path or is there an easier way to add a parameter to this call? Is an intercepter going to work?


Solution

  • This is the easy way for you, if you are using Spartacus 4.1.x

    1 - Create a service that will provide the store code (maybe you already have it)

    2 - Override original configuration for Occ addEntries endpoint to use your additional parameter (e.g., addEntries: 'users/${userId}/carts/${cartId}/entries?storeCode=${storeCode}' )

    3 - Extend OccCartEntryAdapter from Spartacus, inject the service from Step 1 in the constructor, and override add method; the method body will be almost equal as the original Spartacus code, with the additional that you will get the storeCode from the service injected, and you will add it to buildUrl call:

    this.occEndpointsService.buildUrl('addEntries', {
      urlParams: { userId, cartId, storeCode: STORE_CODE },
    });
    

    Please notice that there would be a slight difference if you defined the value to be send inside the body. It won't be on urlParams, but in the body (variable toAdd), just like it's explained below:

    1 - Create a service that will provide the store code (maybe you already have it)

    2 - Extend OccCartEntryAdapter from Spartacus, inject the service from Step 1 in the constructor, and override add method; the method body will be almost equal as the original Spartacus code, with the additional that you will get the storeCode from the service injected, and you will add it to the body:

    const toAdd = {
      quantity,
      product: { code: productCode },
      storeCode: STORE_CODE
    };
    

    UPDATED: If you are using Spartacus 2.1.x, make it with URL query parameters:

    1 - Create a service that will provide the store code (maybe you already have it)

    2 - Extend OccCartEntryAdapter from Spartacus 2.1.8, inject the service from Step 1 in the constructor, and override add method; the method body will be almost equal as the original Spartacus code, with the additional that you will get the storeCode from the service injected, and you will add it to getUrl call:

    this.occEndpointsService.getUrl('addEntries', {
      'addEntries',
      {
        userId,
        cartId,
      },
      { code: productCode, qty: quantity, storeCode: STORE_CODE }
    );
    

    Please let me know. Thanks!