Angular2中的Observable與Ionic2中的Provider、Promise

    隨着Inoic Beta6的發佈[1],對其中的一些技術細節, 重點是ReactiveX庫, Angular2中的Observable, Ionic2中的Provider(或Service)、Promise作了初步的分析。 html

1. 如何查看app使用的是哪個Ionic版本[1]

   方法1: 查看app使用的ionic庫版本:npm view ionic-angular versionreact

   方法2: 查看app根目錄下的package.json文件,能夠看到版本依賴關係,例如:git

    "ionic-angular": "2.0.0-beta.6"
github

2. Components 與 Pages有哪些差別

     參照[2,3], pages是navigation componentin the context of navigation)中的 decorators 。 npm

3. ReactiveX庫中的Observable

    一個Observer向一個Observable來subscribe。Observable會經過調用observers的方法,向observers emits items或發送通知,「observer」也被稱爲「subscriber,」 「watcher,」 或「reactor.」,一般被稱爲觀察者模式、reactor模式等 [6]。
json

    Observables 和Observers僅僅是ReactiveX庫的起點,它不單單只是對標準的觀察者模式的一個小小的擴展,它更適於處理一系列事件而不僅是一次回調函數的調用。api

   真正強大之處在於「reactive extensions」 (所以這個庫被命名爲「ReactiveX」) — 能夠對Observable發佈的一系列items來作大量操做:transform, combine, manipulate等等。promise

   這些Rx operators就能夠用declarative方式將異步序列組合起來,這樣既有回調函數的高效率,又避免了嵌套回調handlers在異步處理中典型的缺陷。這些operators包括:app

    Creating Observables異步

    CreateDeferEmpty/Never/ThrowFromIntervalJustRangeRepeatStart, and Timer

    Transforming Observable Items

    BufferFlatMapGroupByMapScan, and Window

    Filtering Observables

    DebounceDistinctElementAtFilterFirstIgnoreElementsLastSampleSkipSkipLast,Take, and TakeLast

    Combining Observables

    And/Then/WhenCombineLatestJoinMergeStartWithSwitch, and Zip

    Error Handling Operators

         Catch and Retry

    Utility Operators

       DelayDoMaterialize/DematerializeObserveOnSerializeSubscribeSubscribeOn,TimeIntervalTimeoutTimestamp, and Using

    Conditional and Boolean Operators

    AllAmbContainsDefaultIfEmptySequenceEqualSkipUntilSkipWhileTakeUntil, andTakeWhile

    Mathematical and Aggregate Operators

    AverageConcatCountMaxMinReduce, and Sum

    Converting Observables

    To

    Connectable Observable Operators

    ConnectPublishRefCount, and Replay

    Backpressure Operators

        a variety of operators that enforce particular flow-control policies

許多operators處理Observable並返回Observable,這樣這些operators就能夠鏈式一個接一個調用。在鏈中的每一個operator 處理的不是初始的Observable, 而是在修改Observable後,將修改後的Observable依次傳給下一個operator.

    Builder模式也是相似地鏈式調用,但Builder模式中鏈中方法順序是無關的,而Observable operators順序是相關的。

    ReactiveX庫有Java實現RxJava,有JavaScript實現RxJS。

4. Angular2中的Http Service與Observable

    Angular 1中使用Promise異步加載數據,但在Angular 2中使用Observable來處理異步請求 ,Observable類由ReactiveX庫提供。 Angular 2中的Http service是Angular 1中$http的繼承者, http.get( )方法再也不返回一個Promise, 而是返回一個Observable對象。

ngOnInit() {
    this.getFoods();
  } 
  getFoods() {
    this.http.get('/app/food.json')
      .map((res:Response) => res.json())
      .subscribe(
        data => { this.foods = data},
        err => console.error(err),
        () => console.log('done')
      );
  }

    調用http.get( )來執行HTTP請求,返回一個Observable對象,這樣就可使用map( )方法來配置待處理的數據, 使用subscribe( )方法來觀察處理結果。

    因爲Angular不知道須要將response解析爲JSON,須要使用 .map((res:Response) => res.json()) 調用來讓Angular知道. 這個map( )方法也返回一個Observable, 這樣就可使用method chaining.

    調用subscribe( ) 方法來接收output,其中的三個參數都是event handler. 分別是onNext, onError, 和onCompleted. 

  • onNext方法接收HTTP響應數據. Observables支持數據流,能夠屢次調用這個event handler。但對於HTTP請求數據,Observable一般是在一個調用中就返回全部數據。

  • 若是HTTP請求返回一個諸如404的錯誤碼,則onError event handler被調用。

  • Observable將全部的數據都返回完成後,執行onCompleted event handler。這在Http.get() 調用中不多使用,由於須要的全部數據都傳入到onNext handler。

    這三個參數中,onError 和onCompleted是可選參數,但一般onError不能省略,不然一個未捕獲的Error會致使應用中止執行。

5. Ionic2中的Provider、Service、Observable與Promise

    Ionic2中Provider也就是一個Service, 能夠用ionic g provider PeopleService命令來生成一個名稱爲PeopleService的provider 。

    Observable相對Promise有許多優點,所以Angular2中使用了RxJS。而當前Ionic中生成provider代碼時使用的是ng2中的http模塊,它是個observable, 但then( )返回將它轉爲一個promise返回, ionic團隊正在計劃修改。

6.  ionic-native與ngCordoava

    Ionic 2中ionic-native替換了ngCordoava。


參考資料:

[1] Announcing the Release of Ionic 2 Beta 6!, http://blog.ionic.io/announcing-the-release-of-ionic-2-beta-6/

[2] 10 Minutes with Ionic 2: Calling an API, http://blog.ionic.io/10-minutes-with-ionic-2-calling-an-api/

[3] Ionic Docs Nav, http://ionicframework.com/docs/v2/api/components/nav/Nav/

[4] Refactor provider generator to use observables properly #5532, https://github.com/driftyco/ionic/issues/5532/

[5] Angular 2: HTTP, Observables, and concurrent data loading, http://www.metaltoad.com/blog/angular-2-http-observables

[6] Observable, http://reactivex.io/documentation/observable.html

[7] Reactor Guide 中文翻譯, http://reactor.jervyshi.me/index.html

相關文章
相關標籤/搜索