Angular 2服务接口 [英] Angular 2 interface for service

查看:117
本文介绍了Angular 2服务接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想开发一个搜索组件. 这是用例:

I want to developpe a search component. Here is the use case:

  1. 此组件使用搜索的条件参数调用服务.
  2. 该服务调用api端点,并将结果对象返回为 集合.
  3. 该组件在模板中显示结果.
  1. This component calls a service with search's terms parameters.
  2. The service call the api endpoint and returns the resulting objects as a collection.
  3. 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:

  1. SearchInMaleEmployeeService
  2. SearchInFemaleEmployeeService

这两个服务均实现了搜索功能,可返回员工列表. 我想告诉我的组件根据情况提供哪种服务. 在C#中,我们可以使用接口来告诉组件构造函数使用哪个服务.

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.

我该如何在Angular2中做到这一点?

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.

正如您所说,创建两个实现相同ISearchService接口的不同服务.

As you said, create two different services implementing same ISearchService interface.

使用SearchComponent时,请从模块到ServiceComponent提供适当的服务类别.

When using SearchComponent, provide appropriate service class from module to ServiceComponent.

您的SearchComponent看起来像

  constructor(private searchService: ISearchService) {}

当在不同地方使用SearchComponent时,请提供服务实例:

And when using SearchComponent at different places provide service instance:

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

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

有关Angular2依赖项注入的更多信息,此处.

More information about Angular2 dependency injection here.

更新:

如Ben所指出的

提供语句需要编码为

provide('ISearchService', {useClass: SearchInMaleEmployeeService})

并将类注入组件:

constructor(@Inject('ISearchService') private searchService:ISearchService) {}

这篇关于Angular 2服务接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆