skip to Main Content

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)

2

Answers


  1. 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.

    Login or Signup to reply.
  2. First of all you have to have a service/injectionToken to inject it into angular injectionContext. If you have @Injectable() like a person before said it would work.

    Second of all I would have used APP_INITIALIZER like this for setting up a configuration before app starts

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search