【问题标题】:Angular Interface for Service in HTML SelectorHTML 选择器中服务的 Angular 接口
【发布时间】:2020-10-25 05:26:31
【问题描述】:

如何通过 HTML 选择器提供依赖注入?以下答案是通过打字稿。

https://stackoverflow.com/a/40068594/14432516

providers: [
  { provide: ISearchService, useValue: SearchInFemaleEmployeeService}
]

我想在父母的 html 中做类似的事情,并使用男/女员工搜索服务。父组件有这个html。

<app-search-component>
</app-search-component>

我看了可以通过Module来完成吗?但是,该模块在html中多次调用搜索组件,可能需要男性或女性员工搜索服务。

【问题讨论】:

    标签: angular typescript angular10


    【解决方案1】:

    一般来说,依赖注入是一个静态过程,如果你想保持静态,你可以有两个组件&lt;app-search-female-component&gt;&lt;app-search-male-component&gt;,声明如下

    // <app-search-female-component>
    constructor(
        private searchService:SearchInFemaleEmployeeService
    ) {}
    
    // <app-search-male-component>
    constructor(
        private searchService:SearchInMaleEmployeeService
    ) {}
    

    或者用一个参数声明一个搜索组件,给出你想要使用的服务类型

    // <app-search-component type="male">
    @Input()
    public type: string;
    constructor(
        private maleSearchService:SearchInFemaleEmployeeService,
        private femaleSearchService:SearchInMaleEmployeeService,
    ) {}
    

    有很多方法可以实现您想要的。我更喜欢第二个,因为我们在组件内找到了服务的选择。我的意思是在某些时候你必须以编程方式和动态地告诉你想要选择什么搜索类型,如果它被隔离在某个地方是很好的。开关越少越好:)


    编辑:我知道您将在这里有 20-30 个服务,因此您不想在搜索组件中注入 20-30 个服务。 然后您可以创建一个服务SelectorService 用于选择要使用的搜索服务。 这样做,20-30 个服务的注入只进行一次,在SelectorService 中,您的组件只注入一个服务。

    // SelectorService
    constructor(
        private maleSearchService:SearchInFemaleEmployeeService,
        private femaleSearchService:SearchInMaleEmployeeService,
        ...
    ) {}
    
    selectSearchService(type: string): ISearchService {
        switch (type) {
        ....
        }
    }
    
    // <app-search-component type="male">
    @Input()
    public type: string;
    constructor(
        private selector:SelectorService,
    ) {}
    

    【讨论】:

    • 不知道这样行不行,因为我以后可能有20-30种类型,我只提供了一个简单的例子
    • 好的!和20-30会在你父母共存吗?我想知道为什么要进行注射模型。为什么不让一项服务根据参数动态生成搜索端点?
    • 它们可能会根据网络商店等的需要用于许多不同的组件中
    • 我试图编辑我的答案。这是否更符合您的需求?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    相关资源
    最近更新 更多