Patience is key as we wait for another observable to finish using await

Hi everyone, I am facing an issue in my Angular app where I have two methods getA and getB. I have added a third method getC which is dependent on the results from getB. Can someone guide me on how to properly wait for getB to complete before executing getC? My goal is to be able to use the this.B variable in the getC method.

 async ngOnInit() {
      await getA();
      await getB();
      await getC();
 }

getA(): void {
  this.service.fetchA(this.id)
     .pipe(takeUntil(this.ngUnsubscribe))
        .subscribe((res) => {
            {
                this.A = res;
            }
        });

}

getB(): void {
  this.service.fetchB(this.id)
       .pipe(takeUntil(this.ngUnsubscribe))
           .subscribe((res) => {
              this.B = res;
           });
}

getC(): void{
  this.service.fetchC(this.id).subscribe((res) => {
      this.C = this.B + something;
   });
}

Answer №1

Here is an example of how you can approach this problem.

async ngOnInit() {
      fetchDataA();
      fetchDataB();
 }

fetchDataA()....

fetchDataB(): void {
  this.dataService.retrieveDataB(this.id)
       .pipe(takeUntil(this.ngUnsubscribe))
           .subscribe((response) => {
              this.dataB = response;
              fetchDataC();
           });
}

fetchDataC()....

Answer №2

I am struggling to understand the functionality of your services. If these requests are made using HTTP, you will not require an unsubscribe method. If variable A is insignificant, a simple switchMap should suffice:

this.service.fetchB().pipe(
  switchMap((resultFromServiceB:resultTypeB) => 
    this.service.fetchC(resultFromServiceB)
  ),
  tap((resultFromServiceC:'typeOfResultC') => console.log(resultFromServiceC))
).subscribe()

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

How can access to web pages be limited to only logged-in users using Node.js?

Currently, I am attempting to create a filter using tokens in order to limit access to certain pages for unauthenticated users on node.js 0.10. I have implemented a middleware as shown below: app.all( "/product/*" , handler); // will not match /product ...

How to toggle between checked and unchecked states using jQuery within AngularJS?

After reloading, the checkbox should maintain its checked or unchecked state. This functionality can be achieved using a directive controller. var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {}, $checkboxes = $("#c ...

The functionality of Jade views is disrupted by external CSS files

I am new to node.js and apologize if this question seems too obvious. I have built my app logic with all the routes and views, and it was working fine until I tried to add more styles to my views using Jade in Express. The only change I made was including ...

Instructions for opening a URL in a new tab using Angular

Within my Angular 10 application, I am conducting an API call that retrieves an external URL for downloading a pdf file. Is there a method to open this URL in a new browser tab without relying on the window object? I've been using window.open(url) suc ...

What is the best approach to managing undefined properties retrieved from the html in my Angular application prior to obtaining data from my controller?

Every time my Angular component HTML renders, I encounter numerous errors that all look similar to this ERROR TypeError: Cannot read properties of undefined (reading 'someProperty') Throughout my HTML page, there are many bindings that follow ...

Angular does not have the capability to automatically update itself

I have developed an angular project that includes a navigation bar. I would like the navigation bar to automatically update when users log in. I tried using ng-show and ng-hide to control it, but unfortunately, it doesn't seem to work. Can someone hel ...

Encountering an Issue: The formGroup function requires an instance of a FormGroup. Kindly provide one

I am a beginner with Angular 2 and despite reviewing numerous stack overflow answers, I still can't resolve my issue. I have recently started learning about angular reactive forms and wanted to try out my first example but I'm facing some diffic ...

Encountering null injector errors when running ng test on an Angular application

I have successfully developed a webpage in my Angular application and it is running perfectly. But, when I run ng test, some errors are popping up in Karma like the one shown in the image below: https://i.sstatic.net/lUKS5.png superuser.component.ts // ...

Prevent onClick event in jQuery and extract parameters from a function call

We've been tasked with implementing a temporary solution to some code, so it might seem a bit silly at first. But please bear with us. The goal is to block the onclick method of an anchor tag, extract the parameters from the function call, and then u ...

The Mystery of Two Nearly Identical Functions: One function is queued using Queue.Jquery, but the effects fail to work on this particular function. What could be causing this

In short, I am currently working on my first portfolio where I am utilizing Jquery to manipulate text. My goal is to have the text fade in and out sequentially. However, when using the queue function to load another function, the text within the span tag ...

Unable to locate dependencies while testing the react package locally

Recently, I came across this npm package designed for React using Typescript. To debug it locally, I initiated npm link in a new React project but encountered an error: https://i.sstatic.net/nObH6.png I suspect it may not be reading the packages correct ...

Retrieving data values in Typescript

Within my code, I have the following lines placed inside an ngOnInit: this.state.params.subscribe( (params: any) => { console.log("These are the parameters: " + params['id']); if(params['id']){ consol ...

How come the object prototype is appearing as an HTML attribute?

I implemented this functionality (using the version mootools-core-1.4.5.js). Object.prototype.walkRecursive = function(callable, bindable) { var p, val, retVal, _bind; _bind = (typeof bindable === 'object') ? bindable : this; for (p in this) { ...

Exploring RouteReuseStrategy in Angular 2

I followed the RouteReuseStrategy advice provided here, but had to make some adjustments. Specifically, I had to modify the handling of routeConfig.path in the shouldAttach method as it was empty and causing issues with caching. My Angular router version i ...

Tips for integrating tsconfig with webpack's provide plugin

In my project, I have a simple component that utilizes styled-components and references theme colors from my utils.tsx file. To avoid including React and styled-components in every component file, I load them through WebpackProvidePlugin. Everything works ...

Positioning a modal popup to the left in Angular 2

Utilizing This specific modal within Angular2, I am attempting to adjust the positioning of the modal popup to the left. Here is what I have attempted: <modal #categoriesmodal [cssClass]="modalchecklist"> <modal-header [show-close]="true"> ...

Error! Unable to find a compatible version for elements@~0.1.2

Just starting out with Angular and ran into an issue while trying to install packages using 'npm install'. I received the following error message and am unsure how to fix it: npm ERR! notarget No matching version found for elements@~0.1.2. npm ...

Modifying an object's attribute in React.js by toggling a checkbox

As I delve into learning React, I am constructing a straightforward todo list. Here's the object contained within my initialState: getInitialState:function(){ return { items: [ { text:"Buy Fish", ...

Troubleshooting Timeout Problems with Selebiun Crawler in C#

I am encountering an error while running the following code. public void GetCategoriesSelenium() { string javascript = System.IO.File.ReadAllText(@"GetCategory.js"); CrawlerWebSeleniumJS.ExecuteScript("var finished;"); ...

Using jQuery to fetch data from a URL

Imagine having a URL such as: http://localhost:1122/MyProject/MyPage.aspx?from=home&id=454. In the code behind, I can access the 'from' value like Request["from"]. Is there a way to achieve this using JavaScript too? Can jQuery be used for ...