spartacus-storefront

SAP Spartacus NullInjectorError: No provider for CmsComponentData


I am trying to get the component data of a custom component.

private componentData$: Observable<CmsBannerCarouselComponent> = this.componentData.data$.pipe(
    filter(Boolean),
    tap((d: CmsBannerCarouselComponent) => (console.log("++++++++++++++++++++++++++",d)))
  );

I am getting the following error:

core.js:4197 ERROR NullInjectorError: R3InjectorError(AppModule)[CmsComponentData 
    -> CmsComponentData -> CmsComponentData]: 
    NullInjectorError: No provider for CmsComponentData!

Can anyone help me to fix this?


Solution

  • If you use the CmsComponentData in a constructor, it must be provided. This is what Spartacus is doing when a CMS component is placed on the page; while creating the component dynamically, a data object is composed and provided in the injector of that component.

    The CmsComponentData is an abstract class, so if you add a component without injecting a concrete class, you'll face this error.

    We've seen this lately by a dev who wanted to assign the component to a route. This is an example where the Angular will try to fetch a concrete class from the DI system, but there's nothing in Spartacus unless you do this yourself.