我有 2 个对服务器的调用,它们像这样相互依赖
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;
}
);
}
);
但这看起来很丑,有办法让它变得更好吗?
最佳答案
您可以将您的 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();
);
}
);
关于javascript - Angular5,回复并订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48741556/