我有两次对服务器的调用,它们彼此依赖,如下所示
this.service.fetchPoints(this.dateStart, this.dateEnd).subscribe(
response => {
this.points = response;
do something .....
}
);
this.service.fetchSchedule(this.points.date).subscribe(
response => {
this.schedule = response;
}
);this.service的代码如下:
fetchPoints(from:string, to:string) {
return this.http.get(this.createUrl(`/api/congregations/fetch_points/${this.congregation.id}-${from}-${to}`));
}第二个函数也返回observable建立依赖关系的最简单方法是这样编写它
this.service.fetchPoints(this.dateStart, this.dateEnd).subscribe(
response => {
this.points = repsonse;
this.service.fetchSchedule(this.points.date).subscribe(
response => {
this.schedule = response;
}
);
}
);但是这看起来很丑陋,有没有办法让它变得更好呢?
发布于 2018-02-12 16:08:26
你可以将你的Observable转换成一个Promise,但是你将会得到同样的东西。
import 'rxjs/add/operator/toPromise';
fetchPoints(from:string, to:string) {
return this.http.get(this.createUrl(`/api/congregations/fetch_points/${this.congregation.id}-${from}-${to}`))
.toPromise();
}服务:
this.service.fetchPoints(this.dateStart, this.dateEnd).then(
response => {
this.points = repsonse;
this.service.fetchSchedule(this.points.date).then(
response => {
this.schedule = response;
}
);
}
);但是上面的代码并没有真正“整理”太多东西,所以我建议您将fetchSchedule移到它自己的方法中。
另外,在上面的代码中,我注意到您使用了两次限定了作用域的变量response,这非常令人困惑,所以如果您不采纳我的任何建议,我建议您将response更改为类似pointsResponse和scheduleResponse的名称。
private getSchedule() {
this.service.fetchSchedule(this.points.date).subscribe(
response => {
this.schedule = response;
}
);
}然后,您的代码将如下所示:
this.service.fetchPoints(this.dateStart, this.dateEnd).subscribe(
response => {
this.points = repsonse;
getSchedule();
);
}
);https://stackoverflow.com/questions/48741556
复制相似问题