【发布时间】:2019-08-28 22:39:12
【问题描述】:
我正在使用 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;
}
}
【问题讨论】:
标签: javascript jquery angular