我有两次对服务器的调用,这样就相互依赖
self.view.layoutIfNeeded()
this.service是这样的代码:
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;
}
);
第二个函数也返回fetchPoints(from:string, to:string) {
return this.http.get(this.createUrl(`/api/congregations/fetch_points/${this.congregation.id}-${from}-${to}`));
}
最简单的依赖方法就是像这样写
observable
但这看起来很难看,有没有办法让它变得更好?
答案 0 :(得分:0)
您可以将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();
);
}
);