用于服务的 Angular 2 接口 [英] Angular 2 interface for service
问题描述
我想开发一个搜索组件.这是以下用例:
- 此组件使用搜索的术语参数调用服务.
- 服务调用 api 端点并将结果对象作为收藏.
- 组件在模板中显示结果.
我只想编写一个能够根据情况调用不同服务的搜索组件.假设我有两个服务:
- SearchInMaleEmployeeService
- SearchInFemaleEmployeeService
这两个服务都实现了返回员工列表的搜索功能.我想根据情况告诉我的组件哪个服务.在 C# 中,我们可以使用接口告诉组件构造函数使用哪个服务.
我如何在 Angular2 中做到这一点?
额外问题:我如何告诉我的组件根据服务返回的对象类型使用哪个模板来呈现搜索结果?
您可以通过依赖注入来实现这一点.
如您所说,创建两个实现相同 ISearchService
接口的不同服务.
当使用SearchComponent
时,从模块到ServiceComponent
提供适当的服务类.
你的 SearchComponent
看起来像
构造函数(私有搜索服务:ISearchService){}
并且在不同地方使用SearchComponent
时提供服务实例:
提供者:[{ 提供:ISearchService,useValue:SearchInMaleEmployeeService}]
或
提供者:[{ 提供:ISearchService,useValue:SearchInFemaleEmployeeService}]
有关 Angular2 依赖项注入的更多信息此处.>
更新:
正如本所指出的
Provide 语句需要编码为
provide('ISearchService', {useClass: SearchInMaleEmployeeService})
并将类注入到组件中:
constructor(@Inject('ISearchService') private searchService:ISearchService) {}
I want to develop a search component. Here is the following use case:
- This component calls a service with search's terms parameters.
- The service call the api endpoint and returns the resulting objects as a collection.
- The component display the results in the template.
I want to write only one search component able to call different service depending on the case. Imagine I have two service:
- SearchInMaleEmployeeService
- SearchInFemaleEmployeeService
Both of these services implements a search function returning a list of employee. I would like to tell my component which service depending on the case. In C#, we can use interface to tell the component constructor which service to use.
How can I do that in Angular2?
Bonus question: How can I say to my component which template to use to render the search results depending of the type of object returned by the service?
You can achieve this via dependency injection.
As you said, create two different services implementing same ISearchService
interface.
When using SearchComponent
, provide appropriate service class from module to ServiceComponent
.
Your SearchComponent
would look like
constructor(private searchService: ISearchService) {}
And when using SearchComponent
at different places provide service instance:
providers: [
{ provide: ISearchService, useValue: SearchInMaleEmployeeService}
]
or
providers: [
{ provide: ISearchService, useValue: SearchInFemaleEmployeeService}
]
More information about Angular2 dependency injection here.
Update:
As pointed out by Ben
Provide statement needs to be coded as
provide('ISearchService', {useClass: SearchInMaleEmployeeService})
And to inject the class to component:
constructor(@Inject('ISearchService') private searchService:ISearchService) {}
这篇关于用于服务的 Angular 2 接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!