【问题标题】:send synchrouns request angular 6 [closed]发送同步请求角度6 [关闭]
【发布时间】:2019-10-03 00:13:24
【问题描述】:

我想在角度 6 中发送同步请求这个嵌套的 for 循环。所有的 for 循环都必须等待对方的响应。请在https://stackblitz.com中举个例子

protected plateInfo(debug = true) {
      for (let i = 0; i < 8; i++) {
        for (let k = 0; k < 8; k++) {
          if (k % 2 !== 0) {
            for (let threshBlock = 21; threshBlock < 31; threshBlock++) {
              if (threshBlock % 2 !== 0) {
                for (let treshWeight = 5; treshWeight < 19; treshWeight++) {
                  if (treshWeight % 2 !== 0) {
                   this.getPLateInfo.getInfoPlate({
                      qausLast: i,
                      qausParam: k,
                      treshBlock: threshBlock,
                      treshWeight: treshWeight
                    }).subscribe(_data => {
                      this.result.push(_data)
                      _data.input1 = i
                      _data.input2 = k
                    })
                  }
                }
              }
            }
          }
        }
      }
}

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 请不要在您的帖子中添加随机垃圾以绕过 SE 质量限制。相反,添加实际细节。另见How to Ask

标签: javascript angular synchronization angular6


【解决方案1】:

你需要的是一个

concatMap 直到前一个 observable 才订阅下一个 observable 完成,

from([your source array])
    .pipe(
        concatMap(
            (item in your array) => {
                return this.getPLateInfo.getInfoPlate(....
            }
        )
    )
    .subscribe(
        (received data from your api call) => {
            process received data here...
        }
    );

从以下位置导入它们:

import { from } from 'rxjs';
import { concatMap } from 'rxjs/operators';

关于 concatMap 的更多信息here

编辑:

这是一个有效的stackblitz

你原来的“plateInfo”函数会进行1000多个api调用,希望你知道你在做什么。

无论如何,我必须限制数组中的项目数以保持 stackblitz 站点的响应。

【讨论】:

【解决方案2】:

尝试使用等待/异步

async getResult(): MyCustomObject {
    if (typeof this.result === 'undefined') 
    {
        // save result
        this.result = await this.service.call()
        .toPromise()
        .then(resp =>resp as MyCustomObject);//Do you own cast here

    }
    return this.result;
}

【讨论】:

  • 但我使用 angular 6
  • 是的,$q 是 AngularJS 的
  • 但是如何等待这个嵌套for循环的回调结果
猜你喜欢
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-22
  • 2018-06-02
  • 1970-01-01
  • 2019-09-25
相关资源
最近更新 更多