observable需要flatMap()on single()

时间:2017-08-18 19:44:42

标签: angular rxjs observable

每次我认为我理解Observables时,我都不太了解Observables。所以请考虑我在Angular 4应用程序中使用的代码:



// this returns the url to our bitbucket server. the uriService returns
// an Observable<string>
return this.uriService.getBitBucketUrl(path)
  
  // I expect exactly one result, no more, no less, otherwise exception        
  .single() 

  // somehow I still need a flatMap here, to supply the url value into the nested observable
  .flatMap((url: string) => {
    
    // we now have the bitbucket url, use it to get json from it.
    return this.httpService.getJson(url)
      
     // map the result and flatten it to an array
     .flatMap((json: HttpResponse<any>): Array<any> => json.body.values)

     // map each value into a more managed model
     .map<any, BitbucketModel>((value: any) => {
        // create and return BitBucketModel here based on json
 })
});
&#13;
&#13;
&#13;

我希望我能够很好地解释代码,所以它的本质是我不想使用&#39;订阅&#39;任何地方。因为我使用async管道,我想要一直观察到observables。但是当我使用single()然后我必须flatMap它否则它会给我一个错误,因为我无法返回Observable&lt;可观察到的&lt; BitBucketModel&gt;取代。

修改 如果我没有说清楚我要问的内容,我很抱歉。我的方案是我基本上需要一个配置设置,其中我的实际http请求是基于。所以我必须检索该设置并根据该设置执行该实际的http请求。

1 个答案:

答案 0 :(得分:2)

如果我理解正确,你会问为什么flatMap。让我试着解释一下。

  

map同步将输入转换为输出。因此,每个项目都将其转换为其他项目,用新项目替换旧项目。这个过程是同步的。

flatMap也会替换,但会异步执行。

  

flatMap获取一个项目,将其转换为Observable并输出新的Observable蒸汽代替原始项目。

因此可以在这两个实例中使用flatMap(可能是更多应用程序):

  1. 如果输出是异步的(例如url到http呼叫响应)
  2. 如果输出是Observable(例如Array to independent elements)
  3. 前:

    ...'string1'... 'string2'... => 
     ...Output(Observable created from string1)...
     ...Output(Observable created from string2)...
    

    在你的情况下:

    输入:string(url)

    输出:来自异步http调用的json。

    因此,您必须使用flatMap。它与single()

    无关

    另一点:

    在你的例子中:

    .flatMap((json: HttpResponse<any>): Array<any> => json.body.values)
    

    这是同步转换。您正在获取一个对象并同步返回另一个对象。所以它不一定是flatMap。你可以说

    .map((json: HttpResponse<any>): Array<any> => json.body.values)
    

    实际上,您的代码应该给出错误,因为flatMap期望Observable作为返回类型但是您要返回一个对象。

相关问题