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/

相关文章:

javascript - 使用 Angular (2) routerLinkActive 指令进行变形路由

node.js - 无法将 Node.js 应用程序编译到 heroku

javascript - 尝试使用 Angular 创建数据时出现错误

javascript - 展平嵌套的 Observables.subscribe

angular - RXJS 如何在另一个中使用一个 observable 的结果(然后将这两个结果一起处理)

html - 修复 ngx-datatable 中的 header

javascript - 使用 Angular 模板语法传递 SVG 路径

javascript - Angular 5 : Error: macroTask 'requestAnimationFrame'

javascript - 无法使用 Angular 在 html 选择中重置第一项

javascript - Angular 路由仅有时有效