Angular2裡面有用到RxJS的Extensions. 那這個Extendsion會帶給Angular2怎樣的幫助,來研究一下Http的程式碼吧
Angular2 Http Code
1 | import {Response} from './static_response'; |
所以在執行Http.get(…)所回傳的結果是 Observable<Response>
,因為這樣子的關係,我們就可以使用RxJS Observers的方法 參考網址
Subscribe Method
1 | myObservable.subscribe(OnNext,onError,onCompleted); |
onNext
An Observable calls this method whenever the Observable emits an item. This method takes as a parameter the item emitted by the Observable.
onError
An Observable calls this method to indicate that it has failed to generate the expected data or has encountered some other error. It will not make further calls to onNext
or onCompleted
. The onError
method takes as its parameter an indication of what caused the error.
onCompleted
An Observable calls this method after it has called onNext
for the final time, if it has not encountered any errors.
應用方式
Http.call完之後,也可以加工response的結果。方法可以串聯起來, Demo Code如下
1 | this.http.get('xxx') |
多個Http Request時的處理方式
如果想要同時間執行多個Http Request,但是又要等所有的Request都完成後再將資料對應到變數上,那要怎麼寫,這時候就需要使用 Observable.forkJoin,程式碼如下
1 | Observable.forkJoin( |