0

I have a read priority problem in my code. Here, i call a web service, in this web service i put a foreach on an array (listePasseoDemandesEnCours) and I try to recover the username with the userid.

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');)}

and after the foreach, i put the username in another array

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

The problem is that it tries to read the value of Username before the foreach is finished so it is undefined, I would like it to end the foreach and once the value of username != '' Then it the push in the table

  • It's a "clasic question" resolve with switchMap forkJoin and map. SO is full plenty of examples, take a look to [this one](https://stackoverflow.com/questions/67218302/how-to-get-data-for-each-row-of-the-mat-table-asynchronously/67219675#67219675) or [this another](https://stackoverflow.com/questions/65344100/is-there-a-more-efficient-way-to-have-a-subscription-in-a-subscription-in-typesc/65344383#65344383) – Eliseo Aug 26 '21 at 16:59

1 Answers1

0

You just have to put username in another array inside the 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);}         
         }
     });  

  });

Anyway, if you only have 1 possible demandeur, I would do it in this way:

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);

  });