Angular 2 service interface

I want to develop a search component. Here is a usage example:

  • This component calls the service with the parameters of the search parameters.
  • The service invokes the api endpoint and returns the resulting objects as a collection.
  • The component displays the results in a template.

I want to write only one search component that can call a different service, depending on the case. Imagine that I have two services:

  • SearchInMaleEmployeeService
  • SearchInFemaleEmployeeService

Both of these services implement a search function that returns a list of employees. I would like to tell my component what service, depending on the case. In C #, we can use the interface to tell the component constructor which service to use.

How to do this in Angular2?

Bonus question: how can I tell my component which template to use to render search results depending on the type of object returned by the service?

+5
source share
2 answers

You can achieve this through dependency injection.

As you said, create two different services that implement the same ISearchService interface.

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

Your SearchComponent will look like

  constructor(private searchService: ISearchService) {} 

And when using SearchComponent in different places, specify the service instance:

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

or

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

More information on Angular2 dependency injection here .

Update:

As Ben noted

Provise statement must be encoded as

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

And to add a class to the component:

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

Yes, you can do it like Sefa Ümit Oray . But, as I understand it, you are trying to filter two types of objects in a list, and you want to use both of them. So why don't you write a service that has two difference search methods. Or you can write a method that searches in both types of objects.

As you ask, you can use instance of to check the type of an object. Then use Pipe in combination with ngIf to do what you want.

https://angular.io/docs/ts/latest/guide/pipes.html https://angular.io/docs/ts/latest/api/common/index/NgIf-directive.html

+1
source

Source: https://habr.com/ru/post/1258285/


All Articles