Reputation: 4110
I want to develop a search component. Here is the following use case:
I want to write only one search component able to call different service depending on the case. Imagine I have two service:
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?
Upvotes: 7
Views: 9605
Reputation: 8992
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) {}
Upvotes: 12
Reputation: 464
Yes, you can do it like Sefa Ümit Oray answered above. But as I understand, you are trying to filter two type of object in list and you want to use both. So why you don't write a service that has two difference search methods. Or you can write a method that do search in both types of object.
As you ask, you can use instance of
to check the type of object. Then, use Pipe
combine with ngIf
to do render what you want.
https://angular.io/docs/ts/latest/guide/pipes.html https://angular.io/docs/ts/latest/api/common/index/NgIf-directive.html
Upvotes: 2