[英]Wait for loop to finish before executing next line
我正在使用GitHub API检索存储库列表,然后遍历每个存储库,并发出另一个HTTP请求以获取最新的提交日期。 我如何在执行loading = false
之前执行循环以查找最新的提交日期,以便在页面上显示结果?
API.service.ts
export class APIService {
constructor(private http: HttpClient) { }
getRepos(): Observable<any[]>
return this.http.get<any[]>('https://api.github.com/users/githubtraining/repos')
.pipe(catchError(this.handleError));
}
getCommits(url: string): Observable<any> {
return this.http.get<any>(url)
.pipe(catchError(this.handleError));
}
handleError(error: any) {
return throwError(error);
}
}
dashboard.component.ts
export class DashboardComponent implements OnInit {
repos: Repo[];
loading = true;
constructor(private API: APIService) { }
ngOnInit() {
this.getAllRepos();
}
getAllRepos() {
this.API.getRepos().subscribe(data => {
this.repos = data;
for (const repo of this.repos)
{
const commit_url = repo.branches_url.replace('{/branch}', `/${repo.default_branch}`);
this.API.getCommits(commit_url).subscribe(commit => {
repo.last_commit_date = commit.commit.commit.author.date;
});
}
});
// Finish looping over all repos before loading is false
this.loading = false;
}
}
插入this.loading = false;
之后的。 不是在api调用之后
forkJoin
是您的朋友在这里。 它可以采用一个可观察对象数组并将结果解析为一个数组。
getAllRepos() {
this.API.getRepos()
.pipe(switchMap((repos) => {
return forkJoin(repos.map(repo => {
const commit_url = repo.branches_url.replace('{/branch}', `/${repo.default_branch}`);
return this.API.getCommits(commit_url)
.pipe(map(commit => {
repo.last_commit_date = commit.commit.commit.author.date;
return repo;
});
})
})
.subscribe(repos => {
this.repos = repos;
this.loading = false;
});
}
那是怎么回事?
repo
对象中,并返回新的 repo对象。 作为旁注...
使用管道来转换数据。 订阅应用于消费 。 转换管道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.