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

Injectable

標記性元資料,表示一個類別可以由 Injector 進行建立。

Decorator that marks a class as available to be provided and injected as a dependency.

選項說明
providedIn?

透過與 @NgModule 或其他 InjectorType 關聯,或透過指定應在以下注入器之一中提供此可注入物件,來確定將提供該物件的注入器:

Determines which injectors will provide the injectable, by either associating it with an @NgModule or other InjectorType, or by specifying that this injectable should be provided in one of the following injectors:

參見

選項

透過與 @NgModule 或其他 InjectorType 關聯,或透過指定應在以下注入器之一中提供此可注入物件,來確定將提供該物件的注入器:

Determines which injectors will provide the injectable, by either associating it with an @NgModule or other InjectorType, or by specifying that this injectable should be provided in one of the following injectors:

providedIn?: Type<any> | 'root' | 'platform' | 'any' | null
      
      providedIn?: Type<any> | 'root' | 'platform' | 'any' | null
    
  • 'root':在大多數應用程式中是指應用程式級注入器。

    'root' : The application-level injector in most apps.

  • 'platform' :頁面上所有應用程式共享的平臺注入器的特殊單例。

    'platform' : A special singleton platform injector shared by all applications on the page.

  • 'any':在每個延遲載入的模組中提供一個唯一的實例,而所有急性載入的模組共享一個實例。

    'any' : Provides a unique instance in each lazy loaded module while all eagerly loaded modules share one instance.

使用說明

使用 @Injectable 標記一個類別可確保編譯器將在注入類別時產生必要的元資料,以建立類別的依賴項。

Marking a class with @Injectable ensures that the compiler will generate the necessary metadata to create the class's dependencies when the class is injected.

下面的例子展示了如何正確的把服務類別標記為可注入的(Injectable)。

The following example shows how a service class is properly marked so that a supporting service can be injected upon creation.

@Injectable() class UsefulService { } @Injectable() class NeedsService { constructor(public service: UsefulService) {} } const injector = Injector.create({ providers: [{provide: NeedsService, deps: [UsefulService]}, {provide: UsefulService, deps: []}] }); expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true);
      
      @Injectable()
class UsefulService {
}

@Injectable()
class NeedsService {
  constructor(public service: UsefulService) {}
}

const injector = Injector.create({
  providers:
      [{provide: NeedsService, deps: [UsefulService]}, {provide: UsefulService, deps: []}]
});
expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true);