【问题标题】:Access component's provider from another component in angular以角度从另一个组件访问组件的提供者
【发布时间】: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


【解决方案1】:

在组件级别移除提供者,并将其添加到 NgModule 级别的提供者数组中。

    @NgModule({
       providers: [LayerListWidgetService]
    })

组件有自己的注入器,它与同一树中的其他组件形成层次结构。但是如果你将提供者添加到 NgModule 中,它会注册到最近的 NgModule 注入器(要么是延迟加载的模块,要么是根注入器)。使用相同注入器(或分层注入器)的服务可以在也使用相同注入器的组件之间共享。

【讨论】:

  • 我使用组件的提供者,因为我有多个组件实例,我希望每个实例都有自己的服务。
  • 啊,我明白了。我建议有一个根服务来协调(或查找)并订阅子服务。
  • 你有例子吗?我应该如何“找到”提供者的这个特定实例?
  • 我不明白这一点:“我使用组件的提供程序,因为我有该组件的多个实例” - 那么您怎么知道您需要哪个实例用于该“其他”组件?如果你需要的服务就像一个无状态的辅助函数,只需将其设为静态并且不要 DI 服务(只需导入)。
  • @MikeOne 你的问题正是我的问题......我的服务不是一个无状态的辅助函数,它包含我的大部分组件逻辑及其子逻辑 - 我无法摆脱它.. .
猜你喜欢
  • 1970-01-01
  • 2023-01-05
  • 2020-03-22
  • 1970-01-01
  • 2020-10-25
  • 1970-01-01
  • 2018-10-18
  • 2019-08-03
相关资源
最近更新 更多