Angular asynchronous request does not yield any results

After executing ngOnChanges, the method _generateLocationFormForApproval is called, resulting in the output this.absoluteUri. Following this, _pageEventDealsForApprovalList is invoked. However, when trying to access the value of this.absoluteUri inside _pageEventDealsForApprovalList, it returns undefined despite having a value previously set.

What could be causing this.absoluteUri to be undefined inside _pageEventDealsForApprovalList?

Could it be related to asynchronous calls?

#code

  ngOnChanges(changes: SimpleChanges): void {
      if(this.dealId) {
        this._generateLocationFormForApproval();
        this._pageEventDealsForApprovalList();
      }
    }
    
    
    
    private  _generateLocationFormForApproval() {
      this.dealService.generateLocationSubmission(this.dealId)
      .subscribe({
        next: (res) => {
          if (res.isSuccess) {
            this.absoluteUri = res.data.absoluteUri;
          }
        },
        error: err => this.notificationService.showError(err),
        complete: noop,
      });
    }
    
private _pageEventDealsForApprovalList() {
  console.log("1")
  console.log("this.absoluteUrithis.absoluteUri" , this.absoluteUri)
  this.searchInput = '';
  const status = [DEAL.STATUS.FORAPPROVAL, DEAL.STATUS.APPROVED]
  this.dealType = [];
  this.isLoading = true;
  this.dealService
    .getAllDeals(
      status,
      this.accountId,
      this.transaction.id,
      this.table.pageIndex + 1,
      this.table.pageSize,
      this.searchInput,
      this.table.sortParams,
      this.table.sortDirs,
      this.dealType
    )
    .pipe(finalize(() => (this.isLoading = false)))
    .subscribe((res) => {
        if(res) {
          console.log("this.uri" , this.absoluteUri)
        }
    }, (err) => this.notificationService.showError(err)
  );
}

Answer №1

Utilize the Promise method to make two API calls asynchronously.

Here is an example of how you can achieve this:

    ngOnChanges(changes: SimpleChanges): void {
      if(this.dealId) {
        this._generateLocationFormForApproval().then((data)=>{
        console.log(data)
        if(data)
          this._pageEventDealsForApprovalList();
        }
      }
    }
    
private  _generateLocationFormForApproval() {
       return new Promise((resolve,reject)=>{
          this.dealService.generateLocationSubmission(this.dealId)
          .subscribe({
            next: (res) => {
              if (res.isSuccess) {
                this.absoluteUri = res.data.absoluteUri;
                resolve(this.absoluteUri);
              }
            },
            error: err => {
                  this.notificationService.showError(err);
                  reject(err)
            },
            complete: noop,
          });
      })
    }
    
private _pageEventDealsForApprovalList() {
  console.log("1")
  console.log("this.absoluteUrithis.absoluteUri" , this.absoluteUri)
  this.searchInput = '';
  const status = [DEAL.STATUS.FORAPPROVAL, DEAL.STATUS.APPROVED]
  this.dealType = [];
  this.isLoading = true;
  this.dealService
    .getAllDeals(
      status,
      this.accountId,
      this.transaction.id,
      this.table.pageIndex + 1,
      this.table.pageSize,
      this.searchInput,
      this.table.sortParams,
      this.table.sortDirs,
      this.dealType
    )
    .pipe(finalize(() => (this.isLoading = false)))
    .subscribe((res) => {
        if(res) {
          console.log("this.uri" , this.absoluteUri)
        }
    }, (err) => this.notificationService.showError(err)
  );
}

 

Answer №2

If you find yourself in this situation, my suggestion would be to utilize the switchMap function provided by RxJs.

To implement this solution, you can follow a similar approach as outlined below (note: code snippet is theoretical and not tested):

ngOnChanges(changes: SimpleChanges): void {
  // Originally, it looked like this, but for specific changes to dealId, consider using changes.dealId
  if (changes.dealId) {
    this.dealService.generateLocationSubmission(this.dealId)
      .pipe(
        switchMap(res => {
          if (!res.isSuccess) {
            return of(res);
          }
          this.absoluteUri = res.data.absoluteUri;
          return this._pageEventDealsForApprovalList(this.absoluteUri);
        }),
        finalize(() => (this.isLoading = false))
      )
      .subscribe(
        res => {
          if (res) {
            console.log('this.uri', this.absoluteUri);
          }
        },
        err => this.notificationService.showError(err)
      );
  }
}

private _pageEventDealsForApprovalList(absoluteUri): Observable<any> {
  console.log('1');
  console.log('this.absoluteUrithis.absoluteUri', this.absoluteUri);
  this.searchInput = '';
  const status = [DEAL.STATUS.FORAPPROVAL, DEAL.STATUS.APPROVED];
  this.dealType = [];
  this.isLoading = true;
  return this.dealService.getAllDeals(
    status,
    this.accountId,
    this.transaction.id,
    this.table.pageIndex + 1,
    this.table.pageSize,
    this.searchInput,
    this.table.sortParams,
    this.table.sortDirs,
    this.dealType
  );
}

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

Utilizing a function as an argument in another function (with specified parameters)

I’m stuck and can’t seem to solve this problem. In my function, the parameter filter needs to be a function call that accepts an object created within the same function: function bindSlider(time, filter) { var values = { min : 8, max : ...

Utilizing Cordova for Windows 8.1 in Visual Studio 2015 for external image retrieval and insertion into img tag

I am encountering an issue with displaying external images in a Cordova app. While the DOM is functioning correctly, the images are failing to load. I am specifically trying to resolve this for Windows 8.1 only. In my Cordova project for JavaScript, I have ...

Adjust Div Width using a button press

I am attempting to create a functionality where an iFrame will resize in width upon clicking a button. My goal is to have multiple buttons representing breakpoints such as 1024, 680, 480, 380 pixels where the iFrame will adjust its size accordingly. Unfort ...

I am sorry, but there seems to be an issue with the JSON input as it is ending

Whenever I try to submit the form in edit mode, I encounter two errors. An unexpected end of JSON occurred Input provided caused an unexpected end of JSON The update process works perfectly fine and successfully saves values in the database. However, I ...

The checkbox confirmation button appears to be absent in the ngx mat date time picker

I encountered a styling issue with the ngx mat datetime picker in my Angular 15 project. You can find the package here. To resolve the issue, I included @import "https://fonts.googleapis.com/icon?family=Material+Icons"; in my styles.scss file, and that re ...

Exploring the power of Jade and Angular through implementing a for loop within a table structure

I'm brand new to using Jade and Angular, and I could really use a hint from someone more experienced. ... - for (var i = 0; i < p.length; i++) tr td= i + 1 td= price(value='p[i].somedbstuff') ... I want the la ...

What is the method for utilizing enum values as options for a variable's available values?

I'm curious about using enum values in TypeScript to restrict the possible values for a variable. For example, I have an enum named FormType with Create and Update options. Is there a way to ensure that only these enum values are used? enum FormType { ...

What is the best method for utilizing JSON to import Bureau of Labor Statistics information into Highcharts?

When it comes to integrating JSON files into charts, Highcharts offers some helpful examples. However, most of their samples feature rather straightforward JSON files, like this one: pretty simple JSON files. My goal is to take a JSFiddle example (http:// ...

Arranging the button next to the text input field in an Angular application

I added a button labeled "X" to a page, but it is currently positioned below a textfield. How can I use Bootstrap to align the button next to the textfield instead? https://i.sstatic.net/kbX5S.png <div class="form-group row"> <div class ...

Using React.js and TypeScript to leverage a single component for both <input /> and <textarea /> elements

After developing an <Input /> component with helper components for improved usability and code reduction within the main component, I encountered an issue while attempting to create a <textarea /> HTML element. The problem arises from using Rea ...

Creating a connection between my .html and .ejs files: A step-by-step guide

I have successfully created a pair of HTML files - index.html & contact.html. Within these files, I have implemented a navigation bar that allows for seamless transition between them. Recently, I delved into the realm of retrieving APIs and crafted an app ...

Troubleshooting error handling in Node.js using Express and MongoDB

hey there, I'm new to Node.js and I'm working on creating a basic notes app using express and MongoDB. However, I'm encountering an issue when trying to update a note which displays "Cannot PUT" followed by the note's ID. Below is the ...

Navigate directly to the section on the page that discusses the hashtag

So, I have a unique scenario to address. I'm working with two div elements where only one should be visible at a time. Here's the situation: The first div serves as an introduction page with a button that hides it and reveals the second div. Th ...

Struggling to extract text from within a <p> tag on an Ionic 1 app page on iOS

After developing an ionic-1 application for iOS and Android devices, I encountered an issue with displaying mobile numbers in one of the views. The numbers are contained within <p> tags. While users can click and hold on a number to copy it on Andr ...

Best practices for alerting using React and Redux

As I delve into Redux for the first time and work on revamping a fairly intricate ReactJS application using Redux, I've decided to create a "feature" for handling notifications. This feature will involve managing a slice of state with various properti ...

Leveraging jQuery for Adding Text to a Span While Hovering and Animating it to Slide from Left to

<p class="site-description">Eating cookies is <span class="description-addition"></span>a delight</p> <script> var phrases = new Array('a sweet experience', 'so delicious', 'the best treat', ...

What is the best approach for handling an AJAX request on the server side?

Consider the function below: $.ajax({url:"http://127.0.0.1:8080", data: "123", success: function(response, textStatus, jqXHR) { alert(response); }, error: function(jqXHR, textStatus, errorThrown) { alert("An er ...

The functionality of Node async/await appears to be malfunctioning

In an effort to streamline my code and reduce the number of callbacks, I decided to explore using async/await. However, I encountered a problem where Express renders the view before the query is complete. The query results are correct, but they come after ...

Ways to transfer chosen key to a different template

Is there a way to transfer a selected key to another template for displaying a chart? I've developed a template that exports a multi-line chart, utilizing Axios to retrieve data from an API. In the home page, there's a dropdown menu. When a user ...

Javascript - struggling with implementing changeClass() function on click event

I am working on creating movable images within a container using the jQuery plugin found at . My goal is to have items appear within the container when clicked, but I am struggling with changing the class of my object (.item) outside of the container. Th ...