首页 > 解决方案 > 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

标签: javascriptangularrxjs

解决方案


你可以用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);

 });

推荐阅读