Search code examples
javascriptangularinject

inject() Angular making it difficult


How could I be using the inject() functionality in Angular 15 for this case?

  • Way using constructor():
      import { datadogRum } from '@datadog/browser-rum';

      constructor(...) {
          datadogRum.init({
              applicationId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
              clientToken: 'EX-app',
              ...
          });
      }
  • Way using inject():
          import { datadogRum } from '@datadog/browser-rum';

          private datadogRum_ = inject(datadogRum.init);

          ngOnInit() {
                 datadogRum_({
                        applicationId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
                        clientToken: 'EX-app',
                        ...
                  });
          }

Where using inject() causes the following error:

ERROR NullInjectorError: R3InjectorError(AppModule)[function () { -> function () { -> function () {]: 
  NullInjectorError: No provider for function () {!
    at NullInjector.get (core.mjs:7493:27)
    at R3Injector.get (core.mjs:7914:33)
    at R3Injector.get (core.mjs:7914:33)
    at R3Injector.get (core.mjs:7914:33)
    at ChainedInjector.get (core.mjs:12084:36)
    at lookupTokenUsingModuleInjector (core.mjs:3201:39)
    at getOrCreateInjectable (core.mjs:3246:12)
    at ɵɵdirectiveInject (core.mjs:10041:12)
    at ɵɵinject (core.mjs:622:60)
    at inject (core.mjs:705:12)

Solution

  • As you can read in the docs, you can use Angular's dependency injection mechanism only with classes that use Angular decorators, such as @Injectable(), @Component(), @Directive, ... You are trying to inject a function which has no Angular decorator. Angular's DI is not designed to handle those and throws an error, which is totally expected.

    To answer you question: You can't use inject() in this case.