在 Angular 中继续之前等待方法完成

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 事件被触发并且值未定义。有办法吗?

不确定为什么需要时间戳来获取事件,因为根据您的代码,您需要过滤器来获取事件而不是时间戳。但是如果你需要在获得时间戳后调用它,这里是解决方案。

解决方法是在你的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

让我知道这是否适合你。