Waiting for a void method to finish executing before calling another method in Angular with TypeScript

In my Angular component, I have a method that retrieves data using HttpClient subscription. The data is then assigned to an attribute called this.allData. After that, an empty parameter dictionary is instantiated based on this data and passed to another function:

export class TestComponent implements OnInit {

  allData: object[] = []
  activeData: object = {}

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.getData()
    this.makeRequestBasedOnData()
  }

  getData() {
    this.http.get(this.url).subscribe(res => {
      for (let datum of res["data"]) {
        this.allData.push({
          "key": Object.keys(datum)[0],
          "values": Object.values(datum)[0]
        })
        this.activeData[Object.keys(datum)[0]] = "";
      }
    })
  }

  makeRequestBasedOnData() {
    let testParams = this.activeData
    console.log(testParam)
  }

}

I want these operations to occur in sequence. Currently, the testParams logged in makeRequestBasedOnData() displays an empty object {}. Attempting to return arbitrarily within the first method results in a TypeScript error stating that a promise cannot be assigned to type void.

How can I ensure synchronicity in this scenario even though neither method returns anything?

Answer №1

To enhance the functionality of the getData method, you can opt to return an Observable and then continue with other methods inside subscribe:

ngOnInit(): void {
  this.getData().subscribe(() => this.makeRequestBasedOnData());
}

getData() {
  return this.http.get(this.url).pipe(
    tap(res => {
      // update allData
    })
  );
}

The significance of pipe lies in its ability to perform various transformations on data received from the http.get(...) call.

  • tap serves as an rxjs operator designed for side-effects, enabling us to manipulate the response without altering the Observable's flow.

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

JavaScript, where services are injected like Angular's dependency injection

I'm currently developing a Javascript npm package that consists of a single class resembling an angular service. The main goal is to ensure that only one instance of this class is created and can be shared throughout the project as needed. //The Shar ...

Is there a way to eliminate get variables and filename from a URL using JavaScript or jQuery?

I've been researching this issue, but unfortunately, I haven't been able to find a definitive solution for my specific needs. Let's say I have a URL like... How can I extract this URL and remove the "index.php?search=my+search" part so that ...

Chart.js does not support applying custom configurations to the x-axis

Resolved on update 26-04-2021 (see below) I have encountered difficulties with defining the x-axis on Charts.js version 3.1.0. Time is formatted in ISO standard (javascript so): '2021-04-12T01:51:40' Chart configuration options.scaled[scaledId] ...

AJAX should prevent page refresh, but sometimes it forces it

This AJAX test page is a simple demonstration using JQuery. When the page is loaded, it displays a button (BUTTON1). Upon clicking on BUTTON1, it will execute react.php using script.js. The react.php will then replace BUTTON1 with BUTTON2 using a span elem ...

Exploring the possibilities of utilizing a Kendo grid within an ASP.NET Web API

I am currently using the open source edition of Kendo Web with the Kendo UI Web on ASP.NET MVC 4. My Kendo grid contains the following JavaScript code: <script> $(document).ready(function () { $("#grid").kendoGrid({ dataSource: ...

Determine the number of elements that have been modified within a JSON array using jQuery

Being new to the world of web development, I have a question that might sound trivial to those more experienced: I am currently working on creating a wall that showcases a mosaic of 100 miniature landscape pictures. The URLs for these images are fetched f ...

Is it advisable for postcss plugins to list postcss as a peer dependency?

I'm trying to incorporate the PostCSS Sass Color Function into my project. Unfortunately, I encountered this error: PostCSS plugin error: Your current version of PostCSS is 6.0.22, while postcss-sass-color-functions requires 5.2.18. This discrepa ...

Encountering a "subscribe is not a function" error while attempting to utilize a JSON file in Angular 2

My attempt to import a JSON file into my service is resulting in the following error: Error: Uncaught (in promise): TypeError: this._qs.getBasicInfo(...).subscribe is not a function(…) The current state of my service file is as follows @Injectable() ...

Flashing text compatibility across all browsers

I'm looking for a way to create text that blinks on all major web browsers. Initially, I attempted using the <blink> HTML tag, but unfortunately, it only works in Mozilla Firefox. Next, I experimented with CSS: <style> .blink {text-deco ...

Issues with executing JavaScript code within a pop-up window using Selenium IDE

Encountering difficulties while trying to test a pop-up menu using Selenium IDE. The issue arises when attempting to click on a button within the pop-up that triggers a JavaScript function to update a list and close the pop-up. Although the test is progr ...

Issue encountered while submitting form on JQuery Mobile framework

Currently, I am in the process of developing a small web application utilizing JQuery Mobile and Multi Page architecture. The issue arises on my form as the second page. Upon clicking the submit button, an error message is displayed on my console (error i ...

Button-operated lightbox image slider

I am currently developing a website on WAMP where users can store images and view them in a lightbox effect. I have successfully implemented the lightbox effect, but I am facing challenges with moving between images within the lightbox. <html> <? ...

Guide on transforming a tuple of random types into a nested type structure with the help of recursive conditional types

When I responded to the query on whether Typescript Interfaces can express co-occurrence constraints for properties, I shared the following code snippet: type None<T> = {[K in keyof T]?: never} type EitherOrBoth<T1, T2> = T1 & None<T2&g ...

A Guide to Implementing v-for in a JSON Array with Vue.js

After receiving JSON data from the server: [ {"id":"2","name":"Peter","age":"24"}, {"id":"4","name":"Lucy","age":"18"}, ] I am ...

Laravel Behat testing with JavaScript execution without the need for a designated test environment

Currently, I am working on a Laravel 5 project that utilizes Behat for acceptance testing. Moreover, I have set up this project in a Homestead Vagrant box. One of the pages on my website requires Javascript functionality, and I am utilizing the Selenium2 ...

Issues with executing href JavaScript in a Tampermonkey script

I am in the process of creating a script that will adjust the display property of a <td> element. Here is what I have so far: // ==UserScript== // @name Dema VOC hide // @version 0.1 // @include http://mywebsite.com/* // @require ...

Error occurs when attempting to build Angular 5 project with `ng build --prod`

While running ng build --prod, I encountered the following error: The module for class AdminLoginComponent in /var/www/html/ngAngular/src/app/admin-login/admin-login.component.ts cannot be determined! To resolve this, add AdminLoginComponent to the ...

Executing ajax function when the page loads and when a user clicks simultaneously

My external javascript file called ajax.js has an Ajax function like so: function webservice(x){ jQuery.ajax ({ //some code here }); Data = function(data){ if(x==1) ...

Ways to maintain group settings for a Telerik MVC Grid connected to Ajax

Currently, I am seeking guidance on how to persist grouping settings on an Ajax bound Telerik ASP .NET MVC grid. My goal is to have the grid display revert back to its previous settings when a user navigates away to a detail screen and then returns to the ...

Guide on how to import or merge JavaScript files depending on their references

As I work on my MVC 6 app, I am exploring a new approach to replacing the older js/css bundling & minification system. My goal is to generate a single javascript file that can be easily referenced in my HTML. However, this javascript file needs to be speci ...