Angular 2 Observables实施

时间:2016-09-29 02:47:45

标签: angular typescript rxjs observable

我试图用反应式编程方法包装我的逻辑。

我有两个依赖数据集,可能在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之后

有没有办法将结果逻辑放在一个地方(除了在新函数中编写)?

1 个答案:

答案 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));
}