How to use inject outside class in pure function in angular v14?

Viewed 20

I want to inject my FooService and use it only when I click on the button.

But I got this error:

Error: NG0203: inject() must be called from an injection context (a constructor, a factory function or a field initializer)

Is there a way to make it work by inject will be in a separate function?

stackblitz

import { Component, inject, VERSION } from '@angular/core';
import { FooService } from './foo.service';

const load = () => {
  const foo = inject(FooService);
  foo.doSome();
};

@Component({
  selector: 'my-app',
  template: `in app! <button (click)="onClick()">click </button>`,
})
export class AppComponent {
  name = 'Angular ' + VERSION.major;

  onClick() {
    load();
  }
}

1 Answers

I'm afraid this is not possible.

You can find an explanation of the error and all possible valid ways of using inject here.

Related