填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写Home

Injectable

标记性元数据,表示一个类可以由 Injector 进行创建。

Marks a class as available to Injector for creation.

选项说明
providedIn

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 the 'root' injector, which will be the application-level injector in most apps.

参见

选项

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 the 'root' injector, which will be the application-level injector in most apps.

providedIn: Type<any> | 'root' | null
      
      providedIn: Type<any> | 'root' | null
    

使用说明

下面的例子展示了如何正确的把服务类标记为可注入的(Injectable)。

The following example shows how service classes are properly marked as injectable.

范例

@Injectable() class UsefulService { } @Injectable() class NeedsService { constructor(public service: UsefulService) {} } const injector = ReflectiveInjector.resolveAndCreate([NeedsService, UsefulService]); expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true);
      
      @Injectable()
class UsefulService {
}

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

const injector = ReflectiveInjector.resolveAndCreate([NeedsService, UsefulService]);
expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true);
    

Injector在试图实例化一个不带 @Injectable 标记的类时,就会抛出一个错误,如下面的例子所示。

Injector throws an error if it tries to instantiate a class that is not decorated with @Injectable, as shown in the following example.

class UsefulService {} class NeedsService { constructor(public service: UsefulService) {} } expect(() => ReflectiveInjector.resolveAndCreate([NeedsService, UsefulService])).toThrow();
      
      class UsefulService {}

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

expect(() => ReflectiveInjector.resolveAndCreate([NeedsService, UsefulService])).toThrow();