Jul 2, 2015

How to work with Angular 1.x providers

If you try to understand what providers are in angular 1.x, you risk to break your head. I'd broken. Then I fixed it, closed the doc and went to play with js in a sandbox. Today a friend asked me to explain, what the heck is that and to cook it. The explanation took 5 minutes to write a code and write few sentences. Let me share this arcane knowledge with you too.

Question: When do I need to use provider?
Answer: Only if you need to have your service make something during the configuration phase. You don't need set anything up during configuration phase? You don't need a provider. Use factory or service and be happy.

Question: Why I can't use a factory/service during the configuration phase?
Answer: They're not instantiated yet. More details - on the angular site and on stack overflow.

Question: So, during configuration phase I can use only providers?
Answer: Actually, no. You can use constants too. But we're talking about more complex things, right?

JS Bin on jsbin.com

The code is simple and should give full understanding what's going on. All inside the provider is accessible during the cofiguration phase. this.$get is what gets instantiated as a factory/service. The only difference from a factory/service is that it has access to closured date like _config.

Good luck!

No comments:

Post a Comment