2017-03-14 28 views
1

在此ngrx example,searchQuery$是RxJS Observable。據我所知,當用戶界面上的搜索查詢字符串發生更改時,Observable會發出更改。如何從RxJS observable中檢索最新狀態?

我已經介紹另一個Observable調用paging$這個控件來做分頁。這Observable發出頁碼。當頁面發生變化時,我必須撥打另一個服務器電話來檢索剩餘的書籍。

當用戶點擊頁面時,我打電話給服務器,因爲它是直接來自UI,而不是由searchQuery$ Observable發出的搜索字符串。

如何結合searchQuery$paging$來檢索使用RxJS的搜索字符串和頁碼?

UPDATE:

活動:

  1. 用戶類型an在搜索框中。
  2. 顯示前10本書。
  3. 用戶現在單擊NEXT分頁按鈕。
  4. 應該顯示接下來的10本書(在帶有最後搜索字符串an的http請求之後)。

從NGRX例子的代碼:

import 'rxjs/add/operator/let'; 
import 'rxjs/add/operator/take'; 
import { Component, ChangeDetectionStrategy } from '@angular/core'; 
import { Store } from '@ngrx/store'; 
import { Observable } from 'rxjs/Observable'; 

import * as fromRoot from '../reducers'; 
import * as book from '../actions/book'; 
import { Book } from '../models/book'; 

@Component({ 
    selector: 'bc-find-book-page', 
    changeDetection: ChangeDetectionStrategy.OnPush, 
    template: ' 
    <bc-book-search [query]="searchQuery$ | async" [searching]="loading$ | async" (search)="search($event)"></bc-book-search> 
    <bc-book-preview-list [books]="books$ | async"></bc-book-preview-list> 
    ' 
}) 
export class FindBookPageComponent { 
    searchQuery$: Observable<string>; 
    books$: Observable<Book[]>; 
    loading$: Observable<boolean>; 

    constructor(private store: Store<fromRoot.State>) { 
    this.searchQuery$ = store.select(fromRoot.getSearchQuery).take(1); 
    this.books$ = store.select(fromRoot.getSearchResults); 
    this.loading$ = store.select(fromRoot.getSearchLoading); 
    } 

    search(query: string) { 
    this.store.dispatch(new book.SearchAction(query)); 
    } 
} 
+1

downvote不是從我,但有關你的提示問題:請直接在代碼中包含代碼,因爲外部代碼可能會隨時間而改變,或者可能會脫機或鏈接可能中斷。 – olsn

回答

1

你可以使用一個combineLatest

updateBooks$ = Observable.combineLatest(
    this.searchQuery$, 
    this.paging$ 
).do(([searchQuery, paging]: [string, number]) => { 
    ...makeServerRequest or dispatch an action here 
}); 

updateBooks$ 
    // when subscribing in a component directly, don't forget to handle component-destructions: http://stackoverflow.com/questions/42490265/rxjs-takeuntil-angular2-components-ngondestroy 
    .takeUntil(destroyed$) 
    .subscribe(); 

*如果你的代碼是相同的NGRX,例如,您將不得不刪除take(1)從商店選擇searchQuery$

+0

這是否意味着,任何可觀察的將保持它的最新狀態,並可以像上面那樣檢索? –

+1

沒有任何可觀察到的,但是如果您在商店中有'select'語句,則會是這種情況 - 另外:'combineLatest'將保存給定observable的最新狀態,並且每當發生一個包含所有最新狀態的數組時給定的觀測量發射數據。 – olsn

+0

正如我在原始問題中所說的,'''this.searchQuery $'''在用戶界面中沒有改變。只有尋呼事件發生變化。因此,值'''this.searchQuery $'''observable emit是否爲空而不是用戶在UI上輸入的值?我不明白的是沒有'''subject''這個'''observable''發出搜索字符串來結合。 –