Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

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(问候)   ask by graluc translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use forkJoin for this, Dont forget to include(您可以为此使用forkJoin ,不要忘记添加)

import { forkJoin } from 'rxjs'; forkJoin waits for each HTTP request to complete and group's all the observables returned by each HTTP call into a single observable array and finally return that observable array.(forkJoin等待每个HTTP请求完成并将每个HTTP调用返回的所有可观察对象分组到单个可观察数组中,最后返回该可观察数组。) 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); } in your component you can call getAllPlanets(在您的组件中,您可以调用getAllPlanets) this.getPlanetsService.getAllPlanets() .subscribe(res => { console.log(res); }, err => { console.log(err); });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...