首页 > 解决方案 > 等待数据恢复结束后再阅读更多

问题描述

我的代码中有读取优先级问题。在这里,我调用了一个 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 并且一旦用户名的值 != '' 然后它在表中推送

标签: angulartypescriptasynchronousasync-await

解决方案


您只需将用户名放在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);

  });

推荐阅读