【问题标题】:wait for the end of data recovery before reading more等待数据恢复结束后再阅读更多
【发布时间】:2021-08-27 00:04:13
【问题描述】:

我的代码中存在读取优先级问题。 在这里,我调用了一个 Web 服务,在这个 Web 服务中,我在一个数组(listePasseoDemandesEnCours)上放置了一个 foreach,并尝试使用用户 ID 恢复用户名。

this.ws_demandes_en_cours.getDemandesEnCours().subscribe(
  (ws_data: IAPIListeDemandes) => {
    this.isLoading = false;
    this.userId = this.user_info.getUserID();

     ws_data.listePasseoDemandesEnCours.forEach(item => {
      if (this.userId === item.demandeur) {
        this.userName = item.demandeur_nomPrenom;
         console.log(this.userName +' test username');)}

在 foreach 之后,我将用户名放在另一个数组中

this.selectionUser.push(this.userName);
        console.log(this.userName +' test push user in selectionUserArray')

问题是它试图在 foreach 完成之前读取 Username 的值所以它是未定义的,我希望它结束​​ foreach 并且一旦用户名的值 != '' 然后它在表中推送

【问题讨论】:

  • 这是一个用 switchMap forkJoin 和 map 解决的“经典问题”。 SO有很多例子,看看this onethis another

标签: angular typescript asynchronous async-await


【解决方案1】:

您只需将用户名放在另一个数组inside forEach:

this.ws_demandes_en_cours.getDemandesEnCours()
.subscribe(
  (ws_data: IAPIListeDemandes) => {
    this.isLoading = false;
    this.userId = this.user_info.getUserID();

     ws_data.listePasseoDemandesEnCours.forEach(
       item => {
       
         if (this.userId === item.demandeur) {
           this.userName = item.demandeur_nomPrenom;
           if (username != '') {this.selectionUser.push(this.userName);}         
         }
     });  

  });

无论如何,如果您只有 1 个可能的需求者,我会这样做:

this.ws_demandes_en_cours.getDemandesEnCours()
.subscribe(

  (ws_data: IAPIListeDemandes) => {

    this.isLoading = false;
    this.userId = this.user_info.getUserID();

     const userAPI = ws_data.listePasseoDemandesEnCours.find( 
       item => item.demandeur === this.userId
     );
 
    this.userName = userAPI.demandeur_nomPrenom;           
    this.selectionUser.push(this.userName);

  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 2019-10-17
    • 2020-03-29
    • 1970-01-01
    相关资源
    最近更新 更多