• Genel Bakış
@angular/core

Inject

decorator

Parameter decorator on a dependency parameter of a class constructor that specifies a custom provider of the dependency.

API

@Inject(token: string);
@Inject(token: any);

Usage Notes

The following example shows a class constructor that specifies a custom provider of a dependency using the parameter decorator.

When @Inject() is not present, the injector uses the type annotation of the parameter as the provider.

class Engine {}

        @Injectable()
        class Car {
          constructor(public engine: Engine) {} // same as constructor(@Inject(Engine) engine:Engine)
        }

        const injector = Injector.create({
          providers: [
            {provide: Engine, deps: []},
            {provide: Car, deps: [Engine]},
          ],
        });
        expect(injector.get(Car).engine instanceof Engine).toBe(true);
Detaylara atla
div class="docs-parameter-description">
@returnsstring | null

Value of the attribute if it exists, otherwise null.

function inject(token: HostAttributeToken, options: { optional: false; }): string;
@paramtokenHostAttributeToken

A token that represents a static attribute on the host node that should be injected.

@paramoptions{ optional: false; }
@returnsstring

Value of the attribute if it exists.

Usage Notes

In practice the inject() calls are allowed in a constructor, a constructor parameter and a field initializer:

@Injectable({providedIn: 'root'})
export class Car {
  radio: Radio|undefined;
  // OK: field initializer
  spareTyre = inject(Tyre);

  constructor() {
    // OK: constructor body
    this.radio = inject(Radio);
  }
}

It is also legal to call inject from a provider's factory:

providers: [
  {provide: Car, useFactory: () => {
    // OK: a class factory
    const engine = inject(Engine);
    return new Car(engine);
  }}
]

Calls to the inject() function outside of the class creation context will result in error. Most notably, calls to inject() are disallowed after a class instance was created, in methods (including lifecycle hooks):

@Component({ ... })
export class CarComponent {
  ngOnInit() {
    // ERROR: too late, the component instance was already created
    const engine = inject(Engine);
    engine.start();
  }
}
Detaylara atla