Use Provide and UseClass in Angular Providers

InstructorPascal Precht

Share this video with your friends

Send Tweet

In this lesson, we’re going to take a look at how adding the class provide to the providers property of a component to create an actual provider. We’ll learn what a provider specifically does and how we can provide different dependencies with the same token.

Michael Sevestre
~ 8 years ago

I am a bit surprised to see that the component is responsible for saying which implementation should be used for a given service type (provider in Anglular2). This configuration is typically done outside of the component itself when using DI container. e.g. the component would specify that a DataService is required but not which implementation to use.

  • What's your opinion on that?
  • How can this configuration outside of the component be achieved in Angular2?

Cheers, Michael

Raphi
~ 8 years ago

I am a bit surprised to see that the component is responsible for saying which implementation should be used for a given service type (provider in Anglular2). This configuration is typically done outside of the component itself when using DI container. e.g. the component would specify that a DataService is required but not which implementation to use.

  • What's your opinion on that?
  • How can this configuration outside of the component be achieved in Angular2?

Cheers, Michael

I think the answer is that you can create your own custom providers which make decisions about which service to provide. Then you can pass "DataServiceProvider" to the providers array of the component and have DataServiceProvider determine which service to provide. This moves the decision making out of the component

EDIT: Your answer is in the next video :)

Elliot
~ 8 years ago

It's still a little scary to me how with TypeScript, you can make 2 different classes and have them share the same public interface - then not define an interface for them to explicitly extend, but then still use the 2 classes interchangeably. I would've thought that the TypeScript compiler would complain about them not explicitly extending an interface if you've annotated the type explicitly like that.