Really need help on this. I have been trying different things but its not working.
function1() {
return this.apiService.get().pipe(map(data => {
return this.function2();
}));
}
function2() {
const urls = [];
for (let i = 1; i <= 5; i++) {
urls.push(
this.apiService
.get('/users/?page=' + i)
.pipe(map(data => data))
);
}
forkJoin(...urls).subscribe(data => {
data.forEach(element => {
results = results.concat(element.results);
});
return results;
})
}
this.someService.function1().subscribe(data => {
console.log(data);
})
So basically, i want to print out data that i subscribe in function1(). But the results of function1() relying on function2() which another subscribe().
I do know why but just dont know how to solve it.when i run the script i alway get undefined, the reason is because the function1() could not wait the function2() to return the results.
I got stuck here. Thanks,
ANSWER: I figured out that i should not return the results in function2 as an array.
function2() {
const urls = [];
for (let i = 1; i <= 5; i++) {
urls.push(
this.apiService
.get('/users/?page=' + i)
.pipe(map(data => data))
);
}
return forkJoin(urls);
and then based on the output of funtion2, i will do the rest in function1 which is the concat()....
You're going to want switchMap
- Documentation
Once you have the result from function1
, you want to "switch" to waiting on function2
function1() {
return this.apiService.get().pipe(switchMap(function1Data => {
// Send function2 whatever data it needs
// Example:
return this.function2(function1Data.function2Argument).pipe(map(function2Data => {
// Combine function1Data and function2Data as needed
// Example:
const result = {
function1Property: function1Data.property,
function2Property: function2Data.property
};
return result;
}));
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.