我正試圖用反應式編程方法來包裝我的邏輯。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)第一if
的else
和(2)後的類別if
有沒有辦法讓結果邏輯只在一個地方(除了寫入一個新的函數)?
在'storageResult'的第二個else中,您是否向同一端點發出一個http請求,以至於'storageCategories'? – lbrahim
不,storageResults HTTP請求用於另一個API調用。爲了澄清:我需要首先檢查類別。如果它們在本地存儲中可用,則會使用這些值。如果不是,則將發送針對類別的API請求。在這兩種情況下,我都必須檢查localstorage中的'results'值。如果它存在,那麼我們使用它,否則我們需要發送一個API請求來使用另一個API調用收集結果。因爲這些調用是異步的,所以他們做了一個嵌套的回調混亂,我試圖避免並希望使用RxJS方法編寫代碼。我希望它稍微澄清一下這個問題。 – Hassan
請在下面查看我的答案。 – lbrahim