我试图用反应式编程方法包装我的逻辑。
我有两个依赖数据集,可能在localstorage中,也可能不在。但是我需要先计算一个然后计算第二个。
这样的事情:
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)第一个else
的{{1}}和(2)类别if
之后
有没有办法将结果逻辑放在一个地方(除了在新函数中编写)?
答案 0 :(得分: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));
}