注入一個復雜的服務
EzAlgo相當簡單,使用new或者使用Injector來獲得一個實例看起來差別不大。那如果我們的EzApp組件要使用Http服務呢?
第一眼看上去,Http服務顯然是一個真正有用的服務 - 因為看起來相當的復雜 - Http依賴於XHRBackend和BaseRequestOptions,而XHRBackend又依賴於BrowserXHR。
我們可以有兩種方法獲得一個Http的實例,以便通過它獲得網絡訪問的功能:
1. 使用new進行實例化
如果我們使用傳統的new方式創建Http實例,看起來應該是這樣:
1 var xhrbe = new XHRBackend(BrowserXHR); 2 var options = new BaseRequestOptions(); 3 var http = new Http(xhrbe,options);
這沒什么新奇的,就是繁瑣一點。
2. 使用注入器/Injector
如果使用注入器,我們需要向Angular2框架聲明這些層疊的依賴關系:
1 @Component({ 2 appInjector : [ 3 bind(BrowserXHR).toValue(BrowserXHR), 4 XHRBackend, 5 BaseRequestOptions, 6 Http 7 ] 8 })
bind(BrowserXHR).toValue(BrowserXHR)的意思是,如果需要注入BrowserXHR類型的變量,注入這個類本身而非其實例。
原理是這樣,不過Angular2已經提供了一個定義好的變量httpInjectables,我們直接引用就可以了。
Observable
Observable是一種異步編程模式,與Promise不同,Observable等多的是從數據而非行為的角度 來封裝異步代碼。
Http服務的get()方法返回一個Observable對象,可以把Observable對象看做一個可訂閱的數據流,你通過subscribe()方法訂閱以后,每當數據流中有新的數據,你都會得到通知。
例如:
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>appInjector</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 {Inject,Component,View,bootstrap,NgFor} from "angular2/angular2"; 14 //引入Http相關預定義類型 15 import {Http,httpInjectables} from "angular2/http"; 16 17 //EzApp組件 18 @Component({ 19 selector:"ez-app", 20 //注入Http依賴項集合 21 appInjector:[httpInjectables] 22 }) 23 @View({ 24 directives:[NgFor], 25 template:` 26 <div *ng-for="#album of band.albums"><img [src]="album.cover"></div> 27 `, 28 styles:[` 29 img{height:200px;width:200px;} 30 div{float:left;margin:10px;} 31 `] 32 }) 33 class EzApp{ 34 //注入Http實例對象 35 constructor(@Inject(Http) http){ 36 this.band = {}; 37 http.get("api/music.json")//GET請求 38 .map(rsp=>rsp.json())//將相應轉化為JSON格式的數據集 39 .subscribe(data=>this.band=data[0]);//設置band變量為數據集的第一項 40 } 41 } 42 bootstrap(EzApp); 43 </script> 44 </body> 45 </html>