问题
i want to send synchrouns request this nested for loop in angular 6. it all for loop must wait each other response. Please give some example in 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
})
}
}
}
}
}
}
}
}
回答1:
What you need is a
concatMap does not subscribe to the next observable until the previous completes,
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 them from:
import { from } from 'rxjs';
import { concatMap } from 'rxjs/operators';
More info on concatMap here.
EDIT:
Here is a working stackblitz
Your original "plateInfo" function will make more than 1000 api calls, I hope you know what you are doing.
Anyway, I had to limit the number of items in the array to keep stackblitz site responsive.
回答2:
Try using await/async
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;
}
来源:https://stackoverflow.com/questions/56156313/send-synchrouns-request-angular-6