Execute function once the service call has finished

Having a service function that needs to be called

private callService() {
   this.functionOne();
   this.functionTwo();
   this.functionThree();
}

private getOtherInfo() {
   // pure sync here
   this.getId(this.user['data']);
   this.getType(this.name['data']);
}

The aim is to run callService first and then getOtherInfo, but encountering issues reaching the second function.

The functions within callService are structured as below:

private functionOne() {
    this.user['loading'] = true;
    this.service['user'].get().subscribe(data => {
    this.user['data'] = data;
   }
}

private functionTwo() {
    this.name['loading'] = true;
    this.service['name'].get().subscribe(data => {
    this.name['data'] = data;
   }
}
.....

To address the problem, I modified the function like so:

private callService(): Promise<any> {
     return Promise.resolve() => {
      this.functionOne();
      this.functionTwo();
      this.functionThree();
     });
} 

Within ngOnInit() the following logic is implemented:

this.callService().then(()=> this.getOtherInfo());

Despite these changes, the second function remains unreachable.

Answer №1

There is a solution to all this using observables instead of relying on promises...

You should update your three functions as follows:

private functionOne() {
    this.user['loading'] = true;
    return this.service['user'].get();
}

private functionTwo() {
    this.name['loading'] = true;
    return this.service['name'].get();
}

Modify your callService method like this:

private callService(): Promise<any> {
     forkJoin(
      this.functionOne(),
      this.functionTwo(),
      this.functionThree()
     ).subscribe(([user, name, fnThreeData]) => {
       this.user['data'] = user;
       this.name['data'] = name;
       //deal with fnThreeData here
       this.getOtherInfo();
     });
} 

Avoid mixing promises and other methods, rxjs has everything you need. Embracing rxjs will make your life easier in Angular.

Answer №2

The current code seems to have some issues. The functions like functionOne, functionTwo, etc., are not actually returning promises and there is no return statement at all. Also, the .subscribe method is used but its result is not being utilized. By wrapping the functions in promises and resolving them correctly, you should be able to await their results without any problems:

For instance:

private functionOne() {
    return new Promise( (resolve, reject) => {
        this.user['loading'] = true;
        this.service['user'].get().subscribe(data => {
            this.user['data'] = data;
            resolve();
        });
    });
}

private functionTwo() {
    return new Promise( (resolve, reject) => {
       this.name['loading'] = true;
       this.service['name'].get().subscribe(data => {
           this.name['data'] = data;
           resolve();
       });
   });
}

private callService(): Promise<any> {
     return new Promise( async (resolve, reject) => {
      await this.functionOne();
      await this.functionTwo();
      await this.functionThree();
     });
});

This is a structural example of how it can be implemented (not specific to Angular):

function functionOne() {
return new Promise( (resolve, reject) => {
  setTimeout( () => resolve('return from function 1'), 1000);
  })
}
function functionTwo() {
return new Promise( (resolve, reject) => {
  setTimeout( () => resolve('return from function 2'), 1000);
  })
}

async function callAllFunctions() {
const result1 = await functionOne();
  console.log(result1);
  const result2 = await functionTwo();
  console.log(result2);
}

callAllFunctions().then( () => console.log('finished'));

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

Using ngFor in Angular 2-5 without the need for a div container wrapping

Using ngFor in a div to display an object containing HTML from an array collection. However, I want the object with the HTML node (HTMLElement) to be displayed without being wrapped in a div as specified by the ngFor Directive. Below is my HTML code snipp ...

Did Jscript.net already offer many of the same features as TypeScript?

I find myself lacking knowledge about TypeScript. After reading through introductory articles, I fail to see any groundbreaking innovations that justify the widespread praise it has received. [1] In terms of syntax, didn't JScript.net already provide ...

Angular HTTP Client: Akin to utilizing curl with the --user flag for basic authentication

My goal is to connect to an API using Angular's HttpClient. I possess a key: xxyyzz. As per the API's documentation, I should be able to access resources by executing the following curl command: curl --user 'key:' https://rest.apiname ...

There appears to be an issue with the headers not being

Whenever I use HttpClient to send a request, I make sure to set the necessary headers. However, upon checking the network tab in Chrome, I noticed that these headers are not being properly set. Here is the code snippet: request(url: string, method: strin ...

The error message TS2304 is indicating that the name 'Set' cannot be found in electron-builder

I am trying to utilize the AppUpdater feature in electron-builder for my Electron Application. Upon importing the updater in my main.ts file: import { autoUpdater } from "electron-updater" An error is triggered when running the application: node_module ...

Optimal strategies for managing subscriptions in Angular

I'm currently pondering about the concept of angular subscription and unsubscription. The amount of information available on this topic is overwhelming, making it hard for me to navigate through. When is the right time to unsubscribe from a subscript ...

Guide to hosting an Angular 2 client app and Node server app simultaneously on one server

After creating an app in Angular 2 to retrieve data from a database and utilizing node/express to get data from the server and share it with the Angular client, both are currently operating on separate local hosts. How can I integrate them into one proje ...

Implementing conditional wildcard route redirection in an Angular routing module

Is there a way to manage redirect routes when users enter the wrong URL using wildcards controlled by conditions? In my project, I have 3 main modules that are separate, and each of them has specific conditions for user access based on roles. The issue I ...

Troubleshooting a NextJs/TS problem with importing ESM modules

Click here for the Code Sandbox I'm currently in the process of transitioning some code to NextJS 11 / Webpack 5, including certain modules that now exclusively support ECMAScript Modules (esm). Prior to the upgrade, I could easily export all files ...

What strategies can you employ in Angular to reverse the outcome of a guard using canActivate?

As per the Angular documentation regarding canActivate, it appears that you can only utilize canActivate guards to allow navigation to a route if the canActivate function ultimately returns true. Is there any way to specify, "proceed to this route only if ...

Unsure about module loading with system.js and navigating Typescript

I am currently in the process of transitioning an ASP.Net MVC application to Angular2, and I've encountered some perplexing behavior that I can't seem to grasp. Within my Angular2 app, I have a separate Layoutview that allows me to switch betwee ...

Unable to assign the selected attribute to a dynamically loaded Ion-select component in Ionic 2

I'm facing an issue with dynamically loading <ion-select> and setting default selection using the selected attribute. It doesn't seem to work as expected. Can anyone help me understand why? You can view the code on Plunker app/home.page.h ...

Having trouble getting the Rxjs filter operator to work properly with Angular 2 Observables

Here in this Plunker, I am attempting to utilize a filter operator on Angular2 observable (RxJS) inside the member.service.ts file. The observable is fetched through an HTTP request and processed like so: getMembers (): Observable<Member[]> { va ...

What could be causing the ng-if function to continuously loop?

I have encountered an issue where I am passing a boolean function in the ngIf attribute instead of a boolean condition in my HTML template file. This boolean function seems to be repeating itself depending on the amount of data present in the variable &apo ...

Encountering continuous loops during the resolution of sinon, hindering the ability to conduct proper unit testing in node

In an attempt to implement unit testing in Nodejs using sinon, I have recently installed the following libraries: 1 npm i mocha [2] npm i chai [3] npm i sinon Below is the code that I am working with: unitTest-app.js var sinon = require('sinon&a ...

Tips for minimizing delay after user input with Material UI

Background I'm currently working on a website project that includes a carousel of MUI cards using a unique stack as the underlying component. However, I've encountered an issue where there is a noticeable 4-second delay whenever I try to scroll ...

Manipulate streams using pipes

Is there a more elegant solution for handling this particular piece of code? return new Observable(subscriber => { let subscription = this.anotherObservable().subscribe( (next) => { if (this.condition1(next)) { ...

In JavaScript, sort the array of objects based on the key name

I have an array of objects like the following: employees = [ {name: "Tony Stark", department: "IT"}, {name: "Peter Parker", department: "Pizza Delivery"}, {name: "Bruce Wayne", department: "IT"}, {name: "Clark Kent", department: "Editin ...

Converting an HTML page to PDF with Angular using jsPdf and Html2Canvas

[1st img of pdf generated with position -182, 0, image 208,298 ][1]Converting an HTML page to PDF in Angular 8+ using jspdf and Html2canvas has been a challenge. Only half of the page is successfully converted into PDF due to a scaling issue. Printing th ...

Troubleshooting: Vue.js component events not being detected in TypeScript

I'm encountering an issue with receiving events from a barcode reader, which I heavily referenced from a GitHub repository. The problem lies in the fact that the events emitted by the BarcodeScanner component are not being captured by the enclosing c ...