问题
I'm currently trying to make a function where it loops and by using .subscribe I'm getting an array object each time so that later on I can push the data inside an another array. The loop works but the problem is that the results is not what I want because the .subscribe part is printing the first array and then for the rest it's giving me null arrays whereas it suppose to print 20x the same array. I currently started experimenting with angular and to my knowledge of other languages I don't think that it's working good by first printing "Test"x20 and after goes inside the subscribe and printing.
Function:
testingFunction()
{
let i: number = 0;
while(i < 20){
console.log("Test");
this.testService.getAll().subscribe((object: any[]) => {
console.log(object);
})
i++;
}
}
回答1:
Since you are using Angular, you can make use of RxJS operators to handle this scenario. The forkJoin operator will allow you to wait for the while loop operation to be completed before returning all the observables.
This is how you can make use of the operator:
testingFunction() {
let i: number = 0;
const observablesList = [];
while(i < 20){
observablesList.push(this.testService.getAll());
i++;
}
forkJoin(observablesList).subscribe((response) => {
console.log(response);
});
}
来源:https://stackoverflow.com/questions/59908602/how-to-loop-subscribe-observable