Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

typescript - Angular 2 interface for service

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

  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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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) {}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...