【发布时间】:2021-06-09 18:56:00
【问题描述】:
我有一个包含提供程序的组件的库,就像这样-
@Component({
selector: "lib-layer-list-widget",
templateUrl: "./layer-list-widget.component.html",
styleUrls: ["./layer-list-widget.component.css"],
providers: [LayerListWidgetService],
})
export class LayerListWidgetComponent {}
这个组件正在我的 Angular 项目中呈现,并且
该服务具有我想从项目中的组件中使用的方法。
示例:
import {
LayerListWidgetService,
} from "my-lib";
@Component({
selector: "app-example",
templateUrl: "./app-example.component.html",
styleUrls: [],
})
export class AppExampleComponent {
constructor( private layerListWidgetService: LayerListWidgetService) {
let elements = this.layerListWidgetService.getLayerListElements();
}
}
问题是 - 这不能正常工作,因为我在这里引用的实例与作为组件提供者创建的实例不同。
我试图阅读文档并四处搜索,但找不到具体答案。
有没有办法从另一个组件访问一个组件的提供者(在一个库中)?
【问题讨论】:
-
这里的问题是,您是否需要在具有组件级别服务的组件的实际子组件中提供服务?如果是这样,您可以从 Angular (injector.get('name')) 手动获取注入器服务 - 应该 从注入器树(在本例中为父服务)获取它遇到的第一个注入器.只需确保使用 @Optional 装饰它(检查它是否存在) - 以防止紧密耦合。
标签: angular angular7 angular-library angular-providers