1. 程式人生 > >使用Redux和ngrx構建更好的Angular2應用(二)

使用Redux和ngrx構建更好的Angular2應用(二)

建立ItemsService

我們的ItemsService的第一個也是最簡單的迭代,從store中獲取items集合。請注意,我們將我們的專案集合鍵入包含Item物件陣列的Observable。一旦我們開始使用元件中的集合,將我們的陣列包裝成Observable的好處就會變得更加清晰。我們還會將store注入到建構函式中,store中儲存的就是我們之前定義的AppStore。

@Injectable()
export class ItemsService {
  items: Observable<Array<Item>>;
  constructor(private store
: Store<AppStore>) { this.items = store.select('items'); // Bind an observable of our items to "ItemsService" } }

因為我們基本上是處理一個鍵值儲存,所以我們可以通過呼叫store.select(‘items’)來設定this.items。 select方法在我們的集合中返回一個observable。

重要!!我建立了一個服務來從store中提取items集合的原因是因為當我們開始把所有的東西與我們的遠端API進行通訊時,我們將要引入非同步操作。這種抽象使我們能夠在將所有內容交給reducer進行處理之前適應一些潛在的複雜非同步操作。

消費Items

現在我們已經建立了可以使用items集合的ItemsService,我們將在App元件中消費它們。像在ItemsServic兒中一樣,我們需要像這樣宣告items:Observable

export class App {
  items: Observable<Array<Item>>;
  selectedItem: Observable<Item>;
  constructor(private itemsService: ItemsService, private store: Store<AppStore>) {
    this
.items = itemsService.items; // Bind to the "items" observable on the "ItemsService" this.selectedItem = store.select('selectedItem'); // Bind the "selectedItem" observable from the store } }

這裡我們直接將ItemsService中的items賦值給this.items,同時直接通過呼叫store.select(‘selectedItem’)來獲取到selectedItem的值並設定給this.selectedItem。如果回想起來,我們建立了ItemsService來抽象我們的非同步操作當我們處理items集合的時候。管理selectedItem在本質上是完全同步的,因此我無法為其建立一個SelectedItemService。這就是為什麼我在處理items時使用ItemsService,而在獲取selectedItem狀態時直接處理store。您可以建立一個服務來處理這個為了統一,這將是完全合理的。

展示Items

Angular2是為建立小型特定元件設計的。我們的應用程式有兩個子元件稱為ItemsList和ItemDetail,它們分別列出所有記錄和顯示所選記錄的詳細資訊。

@Component({
  selector: 'my-app',
  providers: [],
  template: HTML_TEMPLATE,
  directives: [ItemList, ItemDetail],
  changeDetection: ChangeDetectionStrategy.OnPush
})

在my-app的模版中,我們初始化items-list元件,並將items屬性繫結到我們本地的items集合。這和Angular1.x中的獨立scope類似,因為我們使用items在子元件上建立了一個輸入(input),然後將其繫結到父元件上的任意集合。因為我們正在處理Observable,所以我們可以通過使用非同步管道將更新的值直接傳遞給我們的輸入,從而可以繞開大量的樣板程式碼。說到樣板,我說一個Angular1.x的通用場景,我們通過在controller中呼叫service然後當promise完成之後,我們獲取到結果然後賦值給我們繫結的一個屬性。在Angular2中,我們完全可以跳過這一步,允許管道為我們將非同步操作的結果繫結到我們模版。

<div>
  <items-list [items]="items | async"></items-list>
</div>
<div>
  <item-detail [item]="selectedItem | async"></item-detail>
</div>

在item-detail元件中,我們採取通用的方式,將selectedItem傳遞給item-detail的輸入屬性item。我們現在已經為我們的應用奠定了基礎,現在我們將挖掘一個redux應用程式中資料流的三個主要特徵。