Patience is key as you await the completion of an API call in Angular 14

Within my Angular 14 application, I am faced with a scenario where I need to make two API calls and then combine the results using "combineLatest" from rxjs. The combined data is then assigned to a variable that I must use in a separate function. How can I ensure that this second function is only called once the data has been obtained?

I understand that an immediate solution would be to place the call to the second function inside the "combineLatest" block, but unfortunately, this approach is not feasible for me. Is there a method available to guarantee that the second function is triggered only when the necessary data is present?

Presented below is an excerpt of my code:

this.dataSubscription = combineLatest([aaaSubscription, bbbObservable]).subscribe(result => {
  this.someVariable = result[0];
} 

separateFunction() {
  if(this.someVariable) {
    console.log("Do this")
  }

Answer №1

To handle the completion of an API call, consider creating an observable such as a Subject. After the API call finishes, you can send a flag or data through the subject and then subscribe to it to execute your desired logic. Here's an example implementation: Code Example

Answer №2

Utilize map, flatMap, and switchMap for this scenario

this.dataSubscription = combineLatest([aaaSubscription, bbbObservable]).switchMap((result) => {
    this.someVariable = result[0];
    this.customFunction();
    return of(result);
     }).subscribe(result => {
    // Perform desired actions
} 

customFunction() {
  if(this.someVariable) {
    console.log("Perform this action")
  }

Answer №3

Perhaps the next step is to make a decision?

this.subscription = 
  merge([subscriptionA,observableB])
    .pipe(
      tap(result => this.variable = result[0])
    )
    .subscribe(result => {
      this.executeFunction();
    }); 

executeFunction() {
  if(this.variable) {
    console.log("Perform this action")
  }

Answer №4

When working with RxJs and Angular, it's important to leverage the abundance of operators provided by RxJs and the AsyncPipe in Angular to handle reactive data without mixing it with stateful data management. By embracing a declarative approach, you can streamline your code and ensure efficiency. Any side effects like logging or setting state variables should be handled within a tap operator rather than cluttering the subscribe body.

someVariable$ = combineLatest([aaaSubscription, bbbObservable])
  .pipe(
    map(result => result[0]),
    tap(data => { if(data) console.log("Do this") })
  );

To bind someVariable in your template, use

[bindingAttribute]="someVariable$ | async"
. Alternatively, subscribe to it in either OnInit or AfterViewInit, making sure to include a call to takeUntil with an observable that completes in OnDestroy:

stop$ = new Subject<any>();

ngOnInit() {
  this.someVariable$
    .pipe(
      takeUntil(this.stop$)
    ).subscribe();
}

ngOnDestroy() {
  this.stop$.next(true);
  this.stop$.complete();
}

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

When using Reactjs, it is not possible to update the state using useState within the handleSubmit function

I've encountered a puzzling error and could use some assistance in understanding it better. After calling setServerList(data.data), the data still appears empty when I attempt to use it. export const KernelUpdateSearch = (props: RouteComponentProps) ...

Improprove the performance of an array of objects using JavaScript

Hello there, I am currently in the process of creating an array. this.data = [{ label: 'Total', count: details.request.length, }, { label: 'In-Progress', count: details.request.filter((obj) => obj.statusId === 0 || ob ...

What is the error message "Cannot assign type 'IArguments' to argument"?

Currently employing a workaround that is unfortunately necessary. I have to suppress specific console errors that are essentially harmless. export const removeConsoleErrors = () => { const cloneConsoleError = console.error; const suppressedWarnings ...

When a selection is made in React MUI Virtualized Autocomplete, the autocomplete menu scrolls back to the top

I am currently using reactMUI autocomplete with virtualization because the listbox is expected to contain thousands of items. The virtualization feature works fine, but when I add an onchange function, the listbox automatically scrolls back to the top wh ...

unable to retrieve access-token and uid from the response headers

I am attempting to extract access-token and uid from the response headers of a post request, as shown in the screenshot at this https://i.sstatic.net/8w8pV.png Here is how I am approaching this task from the service side: signup(postObj: any){ let url = e ...

The proper order for logging in is to first validate the login credentials before attempting

I created a custom validation class to verify if a user is logged in before allowing them access to a specific page. However, after implementing this validation, my program no longer routes me to the intended component. Validation.ts export class UserVal ...

Issues with Cloud9 Angular and NodeJS connecting to API on a separate port of the same server

I am currently utilizing an AWS Cloud9 IDE for my project. Angular is running on port 8080, while my NodeJS (with Express) server is running on port 8081. In my Node app.js file, I have set up CORS headers as follows: const app = express(); app.use(expre ...

Unable to connect a unique FormGroup (using ControlValueAccessor) within a FormArray

We are working with two components, referred to as parent and child, both implementing ControlValueAccessor. The parent form is defined as follows: this.formBuilder.group({ children: this.formBuilder.array([]) }) While the child form looks like this: ...

Is it feasible to restrict a generic type using typeguard?

I'm currently working on refining a generic function, where the autocomplete feature recognizes that it's encountering a typeguard, preventing it from revisiting the same code block. I suspect that the issue lies in not restricting the type to th ...

Tips on overcoming errors while attempting to create a copy of an object using Spread, especially when the object's class contains abstract methods

In the code snippet below, there is an abstract class that requires extended classes to implement a specific method. However, when utilizing the "spread" syntax, an error occurs due to the missing implementation of the abstract method. abstract class Test ...

Tips for efficiently parsing multiple JSON files in Typescript while maintaining clean and concise code

Currently, my app is designed to read multiple Json files in Typescript and populate select boxes. However, I am striving to avoid repeating code with the wet (write everything twice) principle and keep things dry (don't repeat yourself). Initially, I ...

Embedding images using a blob or base64 format does not function properly on iOS devices

I'm facing an issue with setting the src of an img tag to display an image. The code snippet below works fine on android, mac, and windows, but it is not functioning correctly on iOS: let base64Image = pageModel.image; this.$currentPageImage.src = `da ...

How about utilizing React's conditional rendering feature?

I'm currently working on a component that displays tournaments and matches, and I'm facing a challenge in implementing a filter option for users to select tournaments by 'league', while still displaying all tournaments if no 'leagu ...

Propagating numerical values through iterative iterations

I am currently facing an issue with passing values as props to a component using the forEach method in JavaScript. In addition to passing the existing values from an array, I also want to send another value that needs to be incremented by 1 for each iterat ...

Typescript decorator specifically designed for abstract generic Container class's child elements

Struggling with Typescript generics in my project, specifically with Typescript 2.6. My goal is to design a MobX store that implements a class decorator for basic authentication checks. This decorator should take a class type derived from the abstract gen ...

Updating a behavior object array in Angular 5 by appending data to the end

After creating a service to share data across my entire application, I'm wondering if it's possible to append new data to an array within the userDataSource. Here is how the service looks: user.service userDataSource = BehaviorSubject<Array& ...

What types of modifications do ViewChildren and ContentChildren QueryLists keep an eye out for?

Imagine you come across the following lines of code: https://i.stack.imgur.com/7IFx1.png And then, in a different section, you stumble upon this code block: https://i.stack.imgur.com/qac0F.png Under what circumstances would () => {} be executed? Wha ...

Exploring Angular's Implementation of D3 Force Simulation

Looking to incorporate a d3 force simulation in my Angular app. I have a run method that initializes and sets simulation options, as well as a ticked method that updates the simulation on each tick. However, I've encountered a few problems with this s ...

Using TypeScript to call Node.js functions instead of the standard way

Can someone assist me with the issue I'm facing? I have developed a default node.js app with express using Visual Studio nodejs tools, and now I am attempting to call the setTimeout function that is declared in node.d.ts. The code snippet in question ...

What steps are involved in launching an outdated Angular project?

Tasked with reviving an old Angular client in my company, I found myself grappling with outdated files and missing configurations. The lack of package.json, package-lock.json, and angular.json added to the confusion, while the presence of node modules in t ...