I am new to rxjs library and struggle with some things related to the library.
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. The function initData needs to return Observable.
My question is how can I change the function above that it will return Observable?
I might have multiple http requests in initData 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);
})
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.
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
. You can use rxjs
operators to perform various transformation to the data
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);
})
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.