简体   繁体   English

如何使函数返回 Observable?

[英]How to make function to return Observable?

I am new to rxjs library and struggle with some things related to the library.我是 rxjs 库的新手,并且在与库相关的一些事情上挣扎。

I have function:我有功能:

  initData(code)
  {  
    this.selectedLot = this.lots.find(x => x.id == code.Id);
    
    this.dataService.getplan(code.Id)
      .subscribe(response => {
        this.plans = response.results;
        this.selectedPlan = this.plans.find(x => x.id == code.homeId);

      }) 
  }

As you can see the function contains service which makes http call and some selection by id from collection.如您所见,该函数包含进行 http 调用的服务,并通过集合中的 id 进行一些选择。 The function initData needs to return Observable.函数 initData 需要返回 Observable。

My question is how can I change the function above that it will return Observable?我的问题是如何更改上面的函数以使其返回 Observable?

Update更新

I might have multiple http requests in initData function:我可能在 initData 函数中有多个 http 请求:

  initData(code)
  {  
    this.selectedLot = this.lots.find(x => x.id == code.Id);
    
    this.dataService.getplan(code.Id)
      .subscribe(response => {
        this.plans = response.results;
        this.selectedPlan = this.plans.find(x => x.id == code.homeId);
      }) 
       
       
       this.userService.getUserData(code.userId, code.placeId)
         .subscribe(resp=> { this.user = resp.results[0] });  

       this.userService.getAreaUrl(code.areaId)
         .subscribe(resp=> { this.areaLogoUrl = resp.results[0] });  
  }

Don't subscribe to the observable, instead just return it不要订阅可观察的,而只是返回它

 initData(code) {  
    this.selectedLot = this.lots.find(x => x.id == code.Id);
    return this.dataService.getplan(code.Id);
 }

If you want to hit api's sequentially (from the comments) make use of concatMap and tap operators.如果您想按顺序(从评论中)点击 api,请使用concatMaptap运算符。

initData(code) {

   return this.dataService.getplan(code.Id).pipe(
      concatMap(e => this.userService.getUserData(code.userId, code.placeId))
          .pipe(tap(resp => this.user = resp.results[0] )),
      concatMap(e => this.userService.getAreaUrl(code.areaId))
          .pipe(tap(resp => this.areaLogoUrl = resp.results[0] ))
   )

}

You can simply return the Observable .您可以简单地返回Observable You can use rxjs operators to perform various transformation to the data您可以使用rxjs运算符对数据执行各种转换

 initData(code)
  {  
    this.selectedLot = this.lots.find(x => x.id == code.Id);
    
    return this.dataService.getplan(code.Id).pipe(
      tap(response => {
        this.plans = response.results;
        this.selectedPlan = this.plans.find(x => x.id == code.homeId);

      })
    ) 
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM