阻止执行到下一行,直到来自 Api 的响应 [重复]

Posted

技术标签:

【中文标题】阻止执行到下一行,直到来自 Api 的响应 [重复]【英文标题】:Block Execution to Next Line Untill Response From Api [duplicate] 【发布时间】:2021-04-08 06:25:54 【问题描述】:

考虑这个调用 api 获取条形图数据的 observable 方法

类:

 export interface AlarmChart 
 chartLabel: string[];
 data: number[][];
 

API 调用

   getBarChartDataV2(period: string): Observable<AlarmChart> 

   for(let x = 0 ;x<severities.length;x++)
    //each severity all values of a week
    var countoFserverity=[];
    
        for(let i = 0 ;i<daysRangeForWeek.length;i++)

        
          let url =  `$this.config.apiCumulocityUrl/alarm/alarms?dateFrom=$daysRangeForWeek[i].dayStart&dateTo=$daysRangeForWeek[i].dayEnd&severity=$severities[x]'`;
    
         url = url.replace(/'/g,'');
         this.callApi(url).subscribe(res=>
          let response:any = res;
            countoFserverity.push(response.alarms.length);
            //add to final when all results came

            
         );
         
         

   //PREVENT GOING TO THIS LINE BEFORE RESPONSE FROM API INSIDE SUBSCRIBE
    data.push(countoFserverity);
    
      
  debugger;
  result = 
  chartLabel: labels,
  data: data,
  ; 

     return result;

 

API 调用者

  callApi(url:string):Observable<any>

   return   this.httpClient.get(url).pipe(
    map(res => 
     debugger;
      let response:any = res;
      return response;
      )
     );
    

【问题讨论】:

您能否重新格式化您的代码示例。很难阅读。 【参考方案1】:

您可以使用 rxjs zip operator,这将在所有 api 调用后触发,类似于以下内容:

   const calls = [];
   for(let x = 0 ;x<severities.length;x++)
    //each severity all values of a week
    var countoFserverity=[];
    
      for(let i = 0 ;i<daysRangeForWeek.length;i++)

      
        let url =  `$this.config.apiCumulocityUrl/alarm/alarms?dateFrom=$daysRangeForWeek[i].dayStart&dateTo=$daysRangeForWeek[i].dayEnd&severity=$severities[x]'`;
  
        url = url.replace(/'/g,'');
        calls.push(this.callApi(url).pipe(
          tap((res) => 
            let response:any = res;
            countoFserverity.push(response.alarms.length);
            //add to final when all results came

            
          )));
        
    
         
   // this wont fire until all calls are done
   zip(...calls).subscribe((values) => 
      values.push(countoFserverity);
   

我没有你的其余代码,所以这是近似的,这是一个可以构建的示例:

const calls = [];
calls.push(this.httpClient.get("https://api.giphy.com/v1/channels/search?q=house&apiKey=Gc7131jiJuvI7IdN0HZ1D7nh0ow5BU6g")
  .pipe(
    tap((val) => console.log(val))
  ));
calls.push(this.httpClient.get("https://api.giphy.com/v1/channels/search?q=house&apiKey=Gc7131jiJuvI7IdN0HZ1D7nh0ow5BU6g"));

zip(...calls).subscribe((val) => 
  console.log(val);
);

【讨论】:

以上是关于阻止执行到下一行,直到来自 Api 的响应 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何阻止用户移动到下一步,直到使用 Angular Material Stepper(Angular 4)完成当前步骤

React JS - 为每个表行调用相同的 API 端点,直到响应包含某些条件

在返回 AJAX 响应之前阻止 Web 浏览器关闭 [重复]

在颤振中调用get api时获得响应但没有获得键值,一些渲染问题,直到我搜索到相同的[重复]

循环直到 TcpClient 响应完全读取 [重复]

在 Python 3.6 中解码来自 API 的文本响应