![](/img/trans.png)
[英]how to make api call complete before moving to another task in angular 2
[英]Await for method to complete before moving on in Angular
我有一個問題,我需要知道如何繼續進行方法的等待。
我在組件中有一個通過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使用時間戳,因為根據您的代碼,您需要針對getEvents而不是時間戳的過濾器。 但是,如果您需要在獲得時間戳記后調用它,這里是解決方案。
解決方案是在完成getTimeStamps之后調用getEvents,而不是在onInit上調用它。
private minTimestamp: Date;
private maxTimestamp: Date;
ngOnInit(): void {
this.getTimestamps();
}
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');
const filters: EventFilters = this.getFilters();
this.dtOptions = this.eventsService.GetEvents(filters);
},
error => {
console.error(error);
this.toastr.error('Fetching source channels filter failed');
}
);
}
因此,基本上,您可以獲取過濾器並在獲得時間戳后調用getEvents
讓我知道這是否適合您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.