javascript - How to manage asynchronous properly
问题描述
my code outputs everytime different numbers. Is this a proper way I am using it? Here is the code:
export class GetPlanetsService {
url='https://swapi.co/api/planets/?page=';
planets:Planet[]=[];
headers: HttpHeaders = new HttpHeaders()
.set('Accept', 'application/json');
constructor(private http:HttpClient) { }
getPlanet(pageIndex){
return this.http.get<Planets>(`${this.url}${pageIndex}`,{headers:this.headers});
}
getAllPlanets(){
let numberOfPages=7; // Tried to do it dynamically but got infinite loop
for(let j=1;j<=numberOfPages;j++){
this.getPlanet(j).subscribe(value=>{
for(let i=0;i<value.results.length;i++){
this.planets.push(value.results[i]);
if(j==numberOfPages && i==(value.results.length-1)){
console.log(this.planets); //There is outputted everytime different number
}
}
});
}
}
Have you got any tips and could you explain it in simple words? Regards
解决方案
你可以用forkJoin
这个,别忘了包括
import { forkJoin } from 'rxjs';
forkJoin 等待每个 HTTP 请求完成,并将每个 HTTP 调用返回的所有 observable 分组到单个 observable 数组中,最后返回该 observable 数组。
getPlanet(pageIndex) {
return this.http.get < Planets > (`${this.url}${pageIndex}`, {
headers: this.headers
});
}
getAllPlanets() {
const response = [...Array(7).keys()].map(i => this.getPlanet(i));
return forkJoin(response);
}
在您的组件中,您可以调用getAllPlanets
this.getPlanetsService.getAllPlanets()
.subscribe(res => {
console.log(res);
}, err => {
console.log(err);
});
推荐阅读
- php - 我正在使用 PHP 将数据插入 mysql DB 并且所有数据都显示为空白并且没有给我任何错误
- java - GIF 以非动画图像的形式共享 - Android Java
- json - (de) 使用 jackson 序列化 kotlin 委托属性
- powershell - 无法更新本地主控目录同步对象的指定属性 - 更新 azure ad 中的用户管理器属性
- javascript - 如何将 django 静态文件放入 javascript 数组中?
- macos - macos下如何检测x86-64程序集中的写错误
- python - 快速计算由 connectedComponents 生成的所有簇的平均颜色
- bash - 如何在bash脚本中为openssl动态生成-extfile参数
- c# - 尝试为 Azure 公共客户端应用程序获取令牌交互时访问被拒绝
- jquery-select2 - 无法将动态数据绑定到 select2 数据源