Injection-Injector
In the example code in the previous section, the component Ezalgo instantiates a Ezalog object directly in the constructor, which results in strong coupling between Ezapp and Ezalgo, which we can decouple using ANGULAR2 's injector/injector :
Injector is like a marriage introduction , the man in the Shang registration of the female characteristics, about good meeting place , then, wait for delivery. Like what:
The Ezapp component (man) uses the Injector attribute of the Component annotation to declare to the ANGULAR2 Framework (Matchmaking Institute) that it relies on Ezalgo (Register the desired female feature), and use the inject annotation declaration injection point in the parameter table of its constructor (about a good meeting place), and then, the rest of the matter Angular2 (Matchmaking office) to do:
1 @Component ({2Selector: "Ez-app",3 //Claim Dependent4 appinjector: [Ezalgo]5 })6 @View (...)7 class ezapp{8 //The ANGULAR2 Framework is responsible for injecting objects9 Constructor (@Inject (Ezalgo) algo) {Ten //We 've got Ezalgo instances! One } A}
For example:
1<!doctype html>234<meta charset= "Utf-8" >5<title>appInjector</title>6<script type= "Text/javascript" src= "Lib/[email protected]" ></script>7<script type= "Text/javascript" src= "Lib/angular2.dev.js" ></script>8<script type= "Text/javascript" src= "Lib/system.config.js" ></script>9Ten<body> One<ez-app></ez-app> A<script type= "Module" > -Import {Inject, component,view,bootstrap} from "Angular2/angular2"; -Import {Formdirectives,control} from "Angular2/forms"; the - //define a simple algorithm service class - class ezalgo{ -Add (A, b) {returnA +b;} +Sub (A, b) {returnA-b;} - } + A //Component Definition at @Component ({ -Selector: "Ez-app", - //appinjector: [Ezalgo] - }) - @View ({ - Directives:[formdirectives], in Template: ' -<form> to<input type= "text" ng-control= "a" [(Ng-model)]= "a" > ++ -<input type= "text" ng-control= "B" [(Ng-model)]= "B" > the= * {{Add ()}} $</form> ',Panax Notoginseng styles:[' -*{font-size:30px;font-Weight:bold;} the input{width:100px;} + `] A }) the class ezapp{ + //Injection Parameter Declaration - Constructor (@Inject (Ezalgo) algo){ $ This. A = 37; $ This. B = 128; - This. Algo =Algo; - } the Add () { - varA = + This. A,WuyiB = + This. b; the return This. Algo.add (A, b); - } Wu } - About Bootstrap (Ezapp, Ezalgo); $</script> -</body> -The output is as follows:
Note: It is also possible to inject ezalgo into the bootstrap function without using appinjector, but there is a difference between them, one in global injection and the other for component injection, with different scopes.
ANGULAR2 Component Development-Invoke service (ii)