2016-09-29 85 views
0

我正試圖用反應式編程方法來包裝我的邏輯。Angular 2 Observables implementation

我有兩個依賴數據集可能或可能不在本地存儲。不過,我需要先計算一個,然後計算第二個。

因此,像這樣:

let storageCategories = this.ls.retrieve('categories'); 
if (storageCategories) { 
    // Found in localStorage 
    this.allCategories = storageCategories; 
} else { 
    // Send an HTTP API request and fetch categories 
    // After request is successful lookup for 'result' in localstorage 
    // If result not in localstorage send an HTTP API request 
} 


// RESULT LOGIC 
let storageResult = this.ls.retrieve('result'); 
if (storageResult) { 
    // Found in localStorage 
    return new BehaviorSubject<any>(this.processResultData(storageResult)); 
} else { 
    // Send an HTTP API request and fetch result 
    // If request is successful save in localstorage and return 
} 

現在的基本問題是我不想寫在兩個地方的結果邏輯:(1)第一ifelse和(2)後的類別if

有沒有辦法讓結果邏輯只在一個地方(除了寫入一個新的函數)?

+0

在'storageResult'的第二個else中,您是否向同一端點發出一個http請求,以至於'storageCategories'? – lbrahim

+0

不,storageResults HTTP請求用於另一個API調用。爲了澄清:我需要首先檢查類別。如果它們在本地存儲中可用,則會使用這些值。如果不是,則將發送針對類別的API請求。在這兩種情況下,我都必須檢查localstorage中的'results'值。如果它存在,那麼我們使用它,否則我們需要發送一個API請求來使用另一個API調用收集結果。因爲這些調用是異步的,所以他們做了一個嵌套的回調混亂,我試圖避免並希望使用RxJS方法編寫代碼。我希望它稍微澄清一下這個問題。 – Hassan

+0

請在下面查看我的答案。 – lbrahim

回答

0

我從你的解釋中提出plunkr here。看看它是否符合你的標準並解決你的問題。這裏是總結:

private getCategories(): Observable<any>{ 
if(this.categoriesInLs){ 
    return Observable.of("categories data"); 
} else { 
    return this.searchService.getCategories(); 
} 
} 

private getResults(): Observable<any>{ 
    if(this.resultsInLs){ 
    return Observable.of("results data"); 
    } else { 
    return this.searchService.getResults(); 
    } 
} 

get(){ 
    this.getCategories() 
    .flatMap(categories => this.getResults()) 
    .subscribe(r => console.log(r)); 
} 
+0

謝謝易卜拉欣! - 我會測試它,讓你知道:)我不知道'Observable.of'方法。所以基本上你已經分解了依賴關係,然後在一個單獨的方法('get()')中重新加入它們。不錯的做法:) – Hassan

+0

也可以做一個例程,但這將是醜陋的 – lbrahim