Outside the observable in Angular, there is a vacant array

Within my Angular application, I am facing an issue with the following code snippet located inside a method:

let cardArray: string[] = [];

this.cardService.getCards().subscribe((cards) => {
  console.log("1", cards);

  for (const card of cards.cards) {
    cardArray.push(card.id);
  }

  console.log("2", cardArray);
});

console.log("3", cardArray);

The challenge here is that the number 3 gets logged before numbers 1 and 2. This results in the array being empty outside the observable but filled inside it. How can I ensure the data is available outside the observable? It is required towards the end of my function.

Thank you!

UPDATE: Additional code has been included

let cardArray: string[] = [];

this.cardService.getCards().subscribe((cards) => {
  cardArray = cards.cards;
});

return this.http.post<Object>(
  url,
  {
    cards: cardArray // <-- at this point, the array is empty
  },
  {
    headers: headers
  }
);

Answer №1

Your code needs some refactoring. Consider the following approach:

this.cardService.getCards()
.pipe(
   mergeMap((cards) => {
      return this.http.post<Object>(
        url,
       {
          cards: cards
       },
       {
          headers: headers
       }
     );
   })
)
.subscribe();

Utilizing RXJS mergeMap here helps in chaining observables asynchronously. Keep in mind that this operation is still asynchronous, so you cannot simply return a result. To consume it higher up, consider something like:

function postCards(): Observable<Object> {
   return this.cardService.getCards()
    .pipe(
       mergeMap((cards) => {
         return this.http.post<Object>(
            url,
            {
              cards: cards
            },
           {
              headers: headers
           }
        );
     })
   );

}


postCards().subscribe();

Further understanding of RXJS operators would be beneficial.


Can we extract an array only with IDs from the getCards method mentioned above?

There are ways to achieve this, but it requires a shift in thinking towards asynchronous operations. Refer to How do I return the response from an asynchronous call? for insights on handling async processes effectively.

Embrace JavaScript's asynchronous nature! Using synchronous approaches in an async environment like browsers can lead to unresponsive UI and execution limitations.

Why avoid sync calls? They impact UI responsiveness as JavaScript runs in the browser's UI thread. Long-running tasks prompt user intervention due to time limits enforced by browsers.

Explore varied async solutions based on your specific array usage requirements.

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

What is the best way to forward all URLs to one central page?

I've recently started working with Angular and I'm currently developing a web app project using Angular 9. I could really use your help with this. My goal is to have a dynamic URL structure for the web app, such as https://www.myMainURL.com/***, ...

How to refresh a specific component or page in Angular without causing the entire page to reload

Is there a way to make the selected file visible without having to reload the entire page? I want to find a cleaner method for displaying the uploaded document. public onFileSelected(event): void { console.log(this.fileId) const file = event.targe ...

Differentiating body classes in Angular 5

I am working on a project with both a login screen and a dashboard screen. The body classes for these screens are different, as shown below: <body class="hold-transition skin-black-light sidebar-mini" > // for dashboard <body class="hold-transi ...

How can one go about constructing abstract models using Prisma ORM?

Among my various prisma models, there are common fields such as audit fields like created_at and updated_at. model User { id Int @id @default(autoincrement()) created_at DateTime @default(now()) updated_at DateTime @updatedAt email ...

Error: Couldn't locate Next.js - TypeScript module

I encountered an error with the image, but I am unsure of the reason behind it. Additionally, the directory is included in the second image. https://i.sstatic.net/knUzH.png import Link from 'next/link'; import { useState } from 'react' ...

Developing a discriminated union by utilizing the attribute names from a different type

In my quest to create a unique generic type, I am experimenting with extracting property names and types from a given type to create a discriminated union type. Take for example: type FooBar = { foo: string; bar: number; }; This would translate t ...

The Angular material Datepicker is encountering a conflict where multiple custom value accessors are trying to match a form control with an unspecified

Recently, I integrated a material datepicker widget into my Angular (7) application. The HTML code for this implementation is provided below. <mat-form-field> <input matInput [matDatepicker]="picker" placeholder="Expiry Date" [formControl]="expi ...

When trying to use ngModel with Angular, an error occurs where the property 'selected' cannot be created on a string

I'm currently attempting to utilize [(ngModel)] in the following manner: <div class="items"> <tbody> <tr *ngFor="let info of this.information"> <td> <input type="checkbox" [(ngModel)]="this.info.n ...

What's the process for validating i18n dictionaries using TypeScript?

Is there a way to enforce type checking on existing keys within dictionaries in react-i18next? This means that TypeScript will provide warnings at compile time if a key does not exist. For example: Let's say we have the following dictionary: { "f ...

Updating the checkbox status in Angular when the radio button value is changed

I need help with a feature where all the checkboxes are checked based on the value of a radio button, and vice versa when an unchecked radio button is clicked. I have tried to implement this functionality using the following code but have not been successf ...

Ways to update column B in ag-Grid following a modification in column A

" section, I have a basic grid displayed with values in the ChildColumn Dropdown list depending on the user's choice in the Parent Column. To illustrate this interaction, if the user selects Option2 in the parent column, List2 will be shown in the Chi ...

Trigger event when ngModel changes

Currently, I am trying to perform a test on a select element... <select [ngModel]="selectedRouters" name="routerName" class="form-control" id="routersSelect" size="12" (ngModelChange)="selectRouters($event)" multiple> <option [value]="route ...

Best Practices for Integrating Angular with Your Custom JavaScript Library

Imagine needing to create a TypeScript function that can be utilized across various components, services, or modules. For example, let's say you want an alert wrapper like this: my_alert(msg); // function my_alert(msg) { alert(msg); } You might hav ...

What are the best practices for utilizing the Express router efficiently?

When building a TypeScript REST API, is there any difference between router.get(); router.post(); router.patch(); router.delete(); ---------------- app.use(); app.use(); app.set(); and router .get() .post() .patch() .delete(); ---------- ...

Encountering issues when launching Node.js application using PM2 and ts-node in production mode

I've run into an issue while trying to use PM2 with ts-node. Whenever I attempt to start my application using PM2, I receive an error message stating that the ts-node interpreter is not found in the PATH. I've experimented with installing ts-nod ...

How is it that void can be assigned undefined?

According to the documentation on typescript, it states that "the one exception being that undefined is also assignable to void". Source Strict null checking mode specifies that null and undefined values are not within the domain of every type and can o ...

Is there a more efficient method for coding this switch/case in TypeScript?

I'm working on a basic weather application using Angular and I wanted some advice on selecting the appropriate image based on different weather conditions. Do you have any suggestions on improving this process? enum WeatherCodition { Thunderstorm ...

Access an external URL by logging in, then return back to the Angular application

I am facing a dilemma with an external URL that I need to access, created by another client. My task is to make a call to this external URL and then return to the home page seamlessly. Here's what I have tried: <button class="altro" titl ...

The ngOnChanges() function fails to detect changes in the boolean @Input value coming from the parent component

Whenever I try to pass a dropdown toggle value to a child component, it works fine when the toggle is true but not when it's false. Despite using ngOnChanges to detect changes, it only picks up on the true values. ChildComponent export class ChildCom ...

Delete the text in MUI's TablePagination component that displays the number of rows per page and the total rows in the table

Currently, I am integrating MUI's tablePagination component into my React table with TypeScript. I am looking to remove/disable the circlemarked text displayed in the image (the picture is an example from MUI). https://i.stack.imgur.com/ib0t2.png Af ...