【问题标题】:How to Return Observable from inside Observable如何从 Observable 内部返回 Observable
【发布时间】:2018-03-17 02:58:54
【问题描述】:

我有这个获取缓存值的代码:

getConfigurations(): Observable<SiteConfiguration[]> {
    return this.storageService.getSiteConfigurations().map(c => {
        if(c) {
            return c;
        }                         
        return this.httpClient.get<SiteConfiguration[]>(this.url + "/config").subscribe(c => c);
    });        
}

我缓存了SiteConfiguration 对象,但如果它不存在则需要去服务器获取它。但是我不能在第一个内返回第二个 observable,因为它会返回一个Observable&lt;Observable&lt;SiteConfiguration[]&gt;&gt;

我确定这是一种常见情况,但我的 google-fu 找不到答案。

【问题讨论】:

标签: angular typescript rxjs observable


【解决方案1】:

你的代码应该是这样的

getConfigurations(): Observable<SiteConfiguration[]> {
    return this.storageService.getSiteConfigurations().flatMap(c => {
        if(c) {
            return Obserbable.of(c);
        }                         
        return this.httpClient.get<SiteConfiguration[]>(this.url + "/config")
    })        
}



getCOnfiguration().subscribe(c => c);

【讨论】:

  • 太棒了!谢谢。我见过flatMap,但不知道它的用途。看到您的代码后,它似乎很明显
  • 花点时间阅读有关 Observables 和 rxjs 的知识,你可以用那个库来做这些事情真是太疯狂了
猜你喜欢
  • 1970-01-01
  • 2019-08-05
  • 2018-12-16
  • 2021-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-15
  • 2017-10-20
相关资源
最近更新 更多