Mittwoch, 18. Mai, 2016
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Finishing Angular TODO application and deploying to production 105<br />
is due to the fact that once you use any obfuscation¹⁸¹ tools (even simple minimization with variable<br />
replacement option) your code will stop working in the second example because dependencies will<br />
get mixed up, and the code in the first example solves this. You will learn more about scope and<br />
controllers as we go on, but if you’re interested feel free to take a detour now and learn more about<br />
scope¹⁸² and controllers¹⁸³ from the official docs (both quite extensive and good).<br />
Dependency injection<br />
Now, this fancy term can be nicely explained with a simple example; say you have a simple Howdy<br />
class which creates an instance of SomeService, and when the greet function is called it checks for<br />
it’s value and if it’s equal to ‘iLoveToReturnUsefulData’ you can do something great further within<br />
your app logic:<br />
1 var Howdy = function() {<br />
2 this.someService = new SomeService();<br />
3 };<br />
4<br />
5 Hello.prototype.greet = function() {<br />
6 var data = this.someService.getData();<br />
7 if (data.value === 'iLoveToReturnUsefulData')<br />
8 //do something great<br />
9 };<br />
And sure, this works well until you want to test this class. You’ll create an instance of the Howdy<br />
class in your test function, but you won’t be able to pass someService object to it. Dependency<br />
injection solves this by moving the responsibility of creating the someService object to the creator<br />
of the Howdy instance, whether it is another object or a test mock object¹⁸⁴:<br />
1 var Howdy = function(someService) {<br />
2 this.someService = someService;<br />
3 };<br />
With this rather small change you’re able to control the behavior of the Howdy class instance outside<br />
of it’s constructor, which is often referred to as inversion of control¹⁸⁵. You can learn more about<br />
DI in the official docs¹⁸⁶. One of the good explanations about how dependency injection works in<br />
AngularJS I found was:<br />
¹⁸¹https://en.wikipedia.org/wiki/Obfuscation_<br />
¹⁸²https://docs.angularjs.org/guide/scope<br />
¹⁸³https://docs.angularjs.org/guide/controller<br />
¹⁸⁴http://en.wikipedia.org/wiki/Mock_object<br />
¹⁸⁵http://en.wikipedia.org/wiki/Inversion_of_control<br />
¹⁸⁶https://docs.angularjs.org/guide/di