Angular 将服务限制在一个组件树上

问题描述

我想实现一项服务,让它只提供给一个命名的组件或模块,而不提供给任何其他组件或模块。

因此,每当有人尝试向另一个组件提供该服务时,他们都会收到错误消息,并且程序不应编译。

有没有办法做到这一点?

提前致谢。

解决方法

如果你将它提供给一个组件,它只会对该组件及其子组件可用:

@Component({
  selector: "component",providers: [Service]
})

参见:https://angular.io/guide/providers#limiting-provider-scope-with-components

一种将范围限制到模块或组件的方法:

@Injectable({ providedIn: HelloComponent })
export class Service {}

所以如果这个组件本身没有子组件,它实际上是唯一可以访问它的命名组件。其他组件将收到注入器错误