Angular2組件開發—調用服務(一)

服務 - 封裝可複用代碼

在Angular2中,服務用來封裝可複用的功能性代碼。好比Http服務,封裝了ajax請求的細節,在不一樣的組件中,咱們只須要調用Http服務的API接口就能夠給組件增長ajax請求的功能了:javascript

Angular2中實現一個服務很是簡單直接 : 定義一個類,而後,它就是服務了:html

1 class EzAlgo{
2     add(a,b){return a+b;}
3     sub(a,b){return a-b;}
4 }

上面的代碼定義了一個至關弱智的算法服務EzAlgo,它有兩個API - add()用來計算兩個數的和,sub()用來計算兩個數的差 。在示例中,組件EzApp依賴於這個服務:java

 

 1 <!doctype html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8">
 5     <title>Service</title>
 6     <script type="text/javascript" src="lib/system@0.16.11.js"></script>
 7     <script type="text/javascript" src="lib/angular2.dev.js"></script>
 8     <script type="text/javascript" src="lib/system.config.js"></script>
 9 </head>
10 <body>
11     <ez-app></ez-app>
12     <script type="module">
13         import {Component,View,bootstrap} from "angular2/angular2";
14         import {formDirectives} from  "angular2/forms";
15         
16         //定義一個簡單的算法服務
17         class EzAlgo{
18             add(a,b) { return a+b; }
19             sub(a,b) { return a-b; }
20         }
21 
22         //組件定義
23         @Component({
24             selector : "ez-app"
25         })
26         @View({
27             directives:[formDirectives],
28             template : `
29                     <form> 
30                         <input type="text" ng-control="a" [(ng-model)]="a"> 
31                         -
32                         <input type="text" ng-control="b" [(ng-model)]="b"> 
33                         =
34                         {{sub()}}
35                     </form>`
36         })
37         class EzApp{
38             constructor(){
39                 this.a = 37;
40                 this.b = 128;
41                 //實例化服務對象
42                 this.algo = new EzAlgo(); 43             }
44             add(){
45                 var a = +this.a,
46                     b = +this.b;
47                 return this.algo.add(a,b);
48             }
49             sub(){
50                 var a = +this.a,
51                     b = +this.b;
52                 return this.algo.sub(a,b);
53             }
54         }
55         
56         bootstrap(EzApp);
57     </script>
58 </body>
59 </html>

輸出以下:ajax

相關文章
相關標籤/搜索