【发布时间】:2018-06-25 18:50:51
【问题描述】:
我有一个问题,我需要知道如何在继续之前等待方法完成。
我在组件中通过 http get 调用:
private minTimestamp: Date;
private maxTimestamp: Date;
ngOnInit(): void {
this.getTimestamps();
const filters: EventFilters = this.getFilters();
this.dtOptions = this.eventsService.GetEvents(filters);
}
private getFilters(): EventFilters {
console.log(this.selectedStartDate);
console.log(this.selectedStartTime);
return { FromTimestamp: new Date(`${this.selectedStartDate} ${this.selectedStartTime}`).toISOString(), ToTimestamp: new Date(`${this.selectedEndDate} ${this.selectedEndTime}`).toISOString()};
}
private getTimestamps() {
this.eventsService.GetMinMaxTimestamp()
.subscribe(
result => {
this.srcChannels = result;
console.log('Src channels loaded');
},
error => {
console.error(error);
this.toastr.error('Fetching source channels filter failed');
}
);
}
在役:
public GetMinMaxTimestamp(): Observable<TimestampBoundaries> {
return this.http.get<TimestampBoundaries>(`${this.endpointsBaseUrl}GetMinMaxTimestamp`);
}
现在的问题是 GetEvents 使用这些日期,而 getTimestamps 稍后完成,然后 get 事件被触发并且值未定义。有什么办法吗?
【问题讨论】:
-
为什么 getEvents 需要 getTimestamps 并不明显。 GetEvents 需要过滤器而不是时间戳。请分享更多代码。但这似乎是一个常见的
switchMap案例 -
尝试像
async asyncMethod() { const data1$ = await this.method1(); const data2$ = await this.method2(); }这样使用async和await这样它会逐行调用来获取数据。假设method1()和method2()将返回 observables