Search code examples
angularclassserviceangular-materialinject

Is it a good thing to Inject Service into a model?


So,

I was working on creating a custom MatTableDataSource.

The Goal was to use custom filter/sorting and to directly integrated** with a custom class.**

And I ran into a problem : I needed to call a function from one of my service.

I found multiples solutions to this :

  • One of them was to make the function "static".

Which make sense for sorting/filtering. You have pure, without dependancy, functions.

  • The other was to inject the service into the models by exporting an Injector from app.module.ts

And this is where I started thinking about it.

  • It feel like it's not a good solution, you don't want to create multiple class with injection.

But on the other side

  • What if the filtering function have dependancy to others functions in the app ?

  • What if, for some reasons, we need API call ?

In theses situations, how should i proceed ?

Or How should I access the instance of my service ?


Solution

  • I'm not certain what it is you want to achieve, but here are some answers to your questions and some basic rules of thumb:

    What if the filtering function have dependancy to others functions in the app ?

    Then you can extract these functions into a shared service and use that service in both spots.

    What if, for some reason, we need API call ?

    Decide who should be responsible for making this API call. Are you using a state manager or services? How does the user interact with your table that tells the app it has to perform an API call? Does that need to be the responsibility of the table/data source, or can this be handled elsewhere? Either way, this might end up in a service that you can inject in the right spot.

    You might go for a BaseCustomDataSource on which you can extend for specific models and within that dataSource you could inject the right service for the job.

    Hope this helps!