angular - 如何添加服务提供者

标签 angular

对于组件(@Component),我可以使用“providers: []”来添加注入(inject) token :

export const WINDOW_TOKEN = new InjectionToken<Window>('Window object');

@Component({
  providers: [
    { provide: WINDOW_TOKEN, useValue: window }
  ]
})
export class ExampleClass {
  constructor(@Inject(WINDOW_TOKEN) private windowObj: Window) {}
}

在这种情况下,我不必为这个简单的注入(inject)创建另一个服务。此外,此WINDOW_TOKEN将仅在ExampleClass中加载和使用。更重要的是,我的测试用例可以通过为 windowObj 创建一个 spy 来测试 window.open()

但是,我如何为服务(@Injectable)做类似的事情?

@Injectable({
  provideIn: 'root'
})
export class ExampleService {
  constructor() {}
}

因此,对于这段代码,我如何创建一个 @Inject 并仅在此 ExampleService 中提供,而是创建另一个 @Injectable 并在根或模块中提供。

最佳答案

您只能在模块级或组件级注册服务

取自 Angular Docs: Providing Services

You must register at least one provider of any service you are going to use. The provider can be part of the service's own metadata, making that service available everywhere, or you can register providers with specific modules or components. You register providers in the metadata of the service (in the @Injectable() decorator), or in the @NgModule() or @Component() metadata

When you register a provider with a specific NgModule, the same instance of a service is available to all components in that NgModule. To register at this level, use the providers property of the @NgModule() decorator.

When you register a provider at the component level, you get a new instance of the service with each new instance of that component. At the component level, register a service provider in the providers property of the @Component() metadata.

如果您想注入(inject)另一个服务范围内的服务,则应该将这两个服务封装在同一个模块中。

例如

@NgModule({
   declarations: [],
   imports: [],
   providers: [ServiceA, ServiceB]
})
export class MyModule{}

在您的服务中,您可以注入(inject)仅在同一服务范围内可用的服务。

@Injectable({})
export class ServiceA{
  constructor(private sb: ServiceB) {}

  //Service methods
}

关于angular - 如何添加服务提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57319511/

相关文章:

node.js - AWS抛出CORS

angular - VSCode tasks.json for ng build --watch

angular - 错误 TS2304 : Cannot find name 'X' in the app. angular 4 项目的 components.ts 和 main.ts 文件

css - 液体在html渲染周围添加红框

angular - @ng-bootstrap NgbDatepicker 遇到 "Can' t 绑定(bind)到 'ngModel' 因为它不是 'ngb-datepicker' 的已知属性“

http - 如何在 Angular 2 中进行 API 调用?

html - Angular 7手动设置背景颜色平铺

angular - CSS3D 对象在整个 3d 对象中可见,并且在旋转场景时不会保持对齐

angular - 无法以 Angular 安装 Bootstrap

javascript - 如何将 Tesseract 导入 Angular2 (TypeScript)