Please refrain from proceeding until the data recovery process is complete

I am currently facing a priority issue in my code. The problem arises when I call a web service and attempt to retrieve usernames based on user IDs from an array (listePasseoDemandesEnCours) using a foreach loop.

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

Following the foreach loop, I store the retrieved usernames in another array.

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

The issue lies in attempting to access the username value before the foreach loop completes, resulting in an undefined value. Ideally, I would like the loop to finish executing and only then check if the username is not empty before pushing it into the array.

Answer №1

To store the username in a separate array, you need to include it inside the forEach loop like this:

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

  });

If there is only one possible demandeur, you can simplify it like this:

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

  });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the process of authentication and authorization at individual route levels within Angular 4 using Keycloak

We have successfully integrated Keycloak with our application and the login and logout flow is functioning properly. However, we are facing an issue with authentication and authorization at the route level. When a user clears their browser session or the s ...

Typescript enhances Solid JS by using the "as" prop and the "component" prop

Hey there, I've been experimenting with solid-js lately and I'm facing a challenge integrating it with typescript. My objective is to make my styling more modular by incorporating it within my components. type RelevantTags = Exclude<keyof ...

Chai expect() in Typescript to Validate a Specific Type

I've searched through previous posts for an answer, but haven't come across one yet. Here is my query: Currently, I am attempting to test the returned type of a property value in an Object instance using Chai's expect() method in Typescript ...

Invoking the callback function within the containing scope in Typescript

I am facing an issue with my Angular component where I have a class that includes common services and functions. While passing some functions as callbacks, the scope is getting lost during execution. Let me demonstrate the problem through the code below: @ ...

Resolving typing complications with Typescript in React higher order components for utilizing an alias for components

Attempting to devise a Higher Order Component (HOC) that can also double as a decorator for the following purpose: Let's say there is a component named "counter" interface ICounterProps { count: number; } interface ICounter<T> extends React ...

Sending information to a personalized mat-grid element using properties

I am currently working on enhancing the functionality of the angular material mat-tree component by building a custom component. The main objective is to create a table with expandable and collapsible rows in a hierarchical structure. I have managed to ach ...

Can you clarify the distinction between calling subscription.unsubscribe() and subscription.remove()?

Currently, I am working with Angular 5 and have successfully subscribed to an observable with the use of the subscribe() method. My concern pertains to whether simply calling the unsubscribe() method on the subscription will be adequate for cleaning up all ...

Angular 2 - utilizing dependency injection to access services from within other services

I have developed two Angular 2 services. One of them is a custom Http class with unique functionality: ServerComms.ts import {Injectable} from 'angular2/core'; import {Http} from 'angular2/http'; @Injectable() export class ServerComm ...

What is the best way to pass an array as a parameter in Angular?

I have set up my routing module like this: const routes: Routes = [ { path: "engineering/:branches", component: BranchesTabsComponent }, { path: "humanities/:branches", component: BranchesTabsComponent }, ]; In the main-contin ...

Encountering the "Not all code paths return a value" TypeScript error when attempting to manipulate a response before returning it, however, returning the response directly works without any issues

Encountering an issue where manipulating/process response and return triggers an error in TypeScript with the message "Not all code paths return a value.". Data is fetched from a backend API using RxJS lastValueFrom operator, along with lodash functions as ...

Deleting multiple rows in TypeORM with PostgreSQL and Node.js (using TypeScript)

Hey there, I'm looking for a way to efficiently erase rows in one go without having to run a loop. Can't seem to figure it out on my own, any assistance would be greatly appreciated. async remove(ids: DeleteEmployeeAnswerDTO): Promise<boolean& ...

Intellisense in VS Code is failing to work properly in a TypeScript project built with Next.js and using Jest and Cypress. However, despite this issue,

I'm in the process of setting up a brand new repository to kick off a fresh project using Next.js with TypeScript. I've integrated Jest and Cypress successfully, as all my tests are passing without any issues. However, my VSCode is still flagging ...

What are the steps to resolve the UglifyJs error stating 'Unexpected token operator'?

When running the following command in my Angular app: > ng build --prod --aot --env=staging I encounter this error message: ERROR in vendor.0625f773941bc83e6748.bundle.js from UglifyJs Unexpected token operator «*», expected punc «(» [vendor.0625 ...

Issue with Angular 5 Application - "Implementations cannot be declared in ambient contexts"

Recently in my Angular 5 project, I started encountering an issue with the observable object. Everything was working smoothly until about a week ago when I began receiving this error message: ERROR in node_modules/rxjs/Observable.d.ts(20,31): error TS1183 ...

Angular Table Expansion Panel: Expanding Your Data in Style

Recently started exploring Angular and struggling to find a straightforward method to incorporate a table with an expansion slider containing dropdown menus. You can view the wireframe design Gif I created using Javascript by visiting this link: https://i ...

Identical property classification across varying levels

I am facing an issue with a hook that requires a specific type: type TJsonData = { message: string; activity: string; }; This type can exist on three different levels, allowing for: { message: "", activity: "" } { someData: { message: "", activity: " ...

When Angular encounters :host-context([dir=rtl]) .ion-float-start, it raises a warning about an unmatched pseudo-class in the context of multiple projects within a single angular.json file

I am currently working on an Angular Project that is being used for two different web apps with separate backends. The frontend remains the same for both projects. However, after adding the second project to the angular.json file, I started receiving some ...

Angular not rendering d3 uniquely when using *ngFor

I am currently working on integrating angular-d3-donut into my web application. Each should have its own SVG(donut). However, when I use *ngFor to generate multiple s with one SVG(donut) each, only one is being created and multiple SVG(donuts) are nested ...

Navigating to a specific section in Angular 6 by scrolling to an

I am having trouble setting up an anchor on my Angular 6 page. When I include the following configuration: imports: [RouterModule.forRoot(routes,{'anchorScrolling': 'enabled',})], I encounter the following error: Unable to assign type ...

The utilization of rxjs' isStopped function is now considered

We currently have this method implemented in our codebase: private createChart(dataset: any): any { if (!this.unsubscribeAll.isStopped) { this.chart = this.miStockChartService.createChart(dataset, this.chartId, this.options, this.extend ...