Search code examples
angularsap-commerce-cloudspartacus-storefrontangularjs-injector

Add to cart customisation


I have a requirement where Add to cart module should cater to additional parameters which are setup in my product model. The Product Display Page captures these additional attributes which needs to be passed along to the cart when the product is added.

I am on Spartacus version 5.2. I referred to this architecture from official docs: enter image description here

The Adapter class (OccCartEntryAdapter) cannot be injectable. So I moved up to Connector layer and tried to extend it like this:

@Injectable()
export class UdxCartEntryConnector extends CartEntryConnector {
    constructor(protected override adapter: UdxOccCartEntryAdapter) {
        alert ("Hello world!");
        super(adapter);
    }
    override add(userId: string, cartId: string, productCode: string, quantity?: number | undefined): Observable<CartModification> {
        alert ("Overriding add at UdxCartEntryConnector");
        return super.add(userId, cartId, productCode, quantity);
    }
}

I have this extended class of mine replaced using provider in app.module.ts like this:

  providers: [
    { provide: CartEntryConnector, useClass: UdxCartEntryConnector }
  ],
  bootstrap: [AppComponent],

Yet, Spartacus is not picking my custom extended Connector class (UdxCartEntryConnector) in runtime. I would like to know if there is a different way to get the Connector classes injected?

Or, a broader question: Is this the right way to customise the Add to cart and Edit cart modules?


Solution

  • The reason why Spartacus is not picking your custom connector is that the CartBaseModule is lazy loaded. The OOTB CartConnector is provisioned later than your UdxCartEntryConnector and shadows it. In order to avoid this behavior you need to either eagerly load the CartBaseModule (in your CartBaseFeatureModule) or create your custom lazy-loaded module. Here you can find how to do it: https://help.sap.com/docs/SAP_COMMERCE_COMPOSABLE_STOREFRONT/eaef8c61b6d9477daf75bff9ac1b7eb4/6ae18e81bc8542b8885bb10bb046d5c8.html?locale=en-US&version=5#customizing-lazy-loaded-modules

    You should also be able to inject a custom CartEntryAdapter. In this case, you should provide CartEntryAdapter instead of OccCartEntryAdapter.