填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

Inject

類別建構函式中依賴項引數上的引數裝飾器,用於指定依賴項的自訂提供者。

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

選項說明
token

一個 DI 令牌,對映到要注入的依賴項。

A DI token that maps to the dependency to be injected.

參見

選項

一個 DI 令牌,對映到要注入的依賴項。

A DI token that maps to the dependency to be injected.

token: any
      
      token: any
    

使用說明

下面的示例顯示了一個類別建構函式,該建構函式使用引數裝飾器指定了依賴項的自訂提供者。

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

如果有 @Inject(),則注入器將引數的型別註解用作提供者。

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);
      
      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);