簡體   English   中英

等待循環完成,然后再執行下一行

[英]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;
        });
}

那是怎么回事?

  1. 我們得到了回購
  2. 我們使用switchMap獲取結果並將其轉換為另一個可觀察的結果
  3. 我們使用forkJoin將存儲庫數組轉換為可觀察變量數組,將其分解為單個可觀察變量
  4. 我們使用map將最后一次提交添加到我們的repo對象中,並返回新的 repo對象。

作為旁注...

使用管道來轉換數據。 訂閱應用於消費 轉換管道。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM