[英]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.