Angular is patiently waiting for the initial function to activate

I have a situation where I need to wait for the results of my first function before executing the second one.

code

First function

getUser() {
    this.authService.user().subscribe(
        user => {
        this.user = user;
        console.log('current user 1: ', user);
        console.log('current user 2: ', this.user);
        }
    );
}

async ngOnInit() {
    this.socket.fromEvent('message').subscribe(async (message: any) => {
        if(this.user === undefined) {
            // call the first function
            this.getUser();
            // this console log will fire before the function finishes, resulting in 'undefined'
            console.log('this user: ', this.user);
        } else {
            //....
        }
    }
}

I need to delay my console call until this.getUser(); is completed. What is the best way to achieve this?

Answer №1

If you want to transform your getUser() method into a promise, you can do it like this:

getUser():Promise<any>{
   return new Promise((resolve,reject) =>{
     this.authService.user().toPromise().then(user => {
       this.user = user;
       console.log('current user 1: ', user);
       console.log('current user 2: ', this.user);
       resolve(user);
     }).catch(err=> reject(err));
   });
}

Then, in your ngOnInit():

async ngOnInit(){
  this.socket.fromEvent('message').subscribe(async (message: any) => {
    if(this.user === undefined) {
        // first function called
        await this.getUser().then(user=>{
           console.log('this user: ', user);
        });
    }
  });
}

Additionally, consider using toPromise() when you only need data from an observer once. Subscribing to an observer without unsubscribing can result in memory leaks.

Answer №2

When utilizing combineLatest

combineLatest(this.authService.user(), this.socket.fromEvent('message'))
  .subscribe(([user, message]) => {
    // You can access both the message and user simultaneously
  });

Answer №3

To resolve the issue, make sure to include 'await' in your code as shown below:

async ngOnInit() {
this.socket.fromEvent('message').subscribe(async (message: any) => {
    if(this.user === undefined) {
        // first function called
        await this.getUser();
        // The console log will fire before the function finishes, returning 'undefined'
        console.log('this user: ', this.user);
    } else {
        //....
    }
}}

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

After swapping out "div" with "input" and then replacing "input" with

My goal is to create a function where a user can edit text within a div. The idea is to replace the current text with an editable input field, and then convert it back into a div after the user hits enter. I've encountered an issue while trying to im ...

Angular: What is the best way to populate a column in a table with individual dropdown menus in each cell, each containing unique values?

I am completely new to Angular and I am attempting to build a table to display user information. <div ng-controller="ContactController as cc" ng-app="MyApp" id="account-settings-page"> <div class="slds manage-account-table"> <table class="s ...

HammerJS swipe functionality does not seem to be functioning properly on elements that have the overflow CSS

UPDATE: The code snippet works smoothly when embedded in the question, but encounters issues when edited. This led me to discover that the problem lies with underlying containers that require scrolling... After testing it on my phone, I found that Hammer f ...

React-Router failing to properly unmount components when the location parameter changes

I'm struggling with a frustrating issue - I have a simple app created using create-react-app and I'm utilizing React-Router. JSX: <Router> <Route path="/pages/:pageId" component={Page} /> </Router> Within the Page ...

Implementing AJAX to dynamically update information based on user's selection from a dropdown

I need to dynamically adjust the opacity of my graph bars without requiring the user to manually refresh the page. I'm considering using AJAX for this purpose. How can I implement this functionality? const opacitySlider = document.getEle ...

Looking for a way to utilize a Devise user account in an unconfirmed or locked state for AJAX interactions?

Currently, I am attempting to integrate the devise views utilizing JS to manage the responses. While I aim to utilize the default devise error messages, I am facing difficulty in isolating individual types of errors such as unconfirmed or locked accounts d ...

The IE9 confirmation dialog fails to pause for user response, resulting in automatic postback before user input is received

Behind the Scenes btnNext.Attributes.Add("onclick", " return Verification(this,'" + GetLocalResourceObject("message").ToString() + "'); ") .ASPX Page [Within javascript tags] function Verification(source, message) { var dialog = '< ...

Tips for increasing the number of inputs within a form using <script> elements

I am currently working on a form within the script tags and I would like to include additional input fields before submitting. However, the submit button seems to be malfunctioning and I suspect that there may be an issue with how I am accessing it in my c ...

How do I retrieve URL parameters in Vue.js?

Hello, I am currently working on creating my own websites and I am new to vue.js. I am having trouble getting parameters from the URL. I have tried multiple methods but none seem to work. Here is an example URL: example.com:8080/login. On this page, there ...

Guide on executing get, modify, append, and erase tasks on a multi-parameter JSON array akin to an API within Angular

I have a JSON array called courseList with multiple parameters: public courseList:any=[ { id:1, cName: "Angular", bDesc: "This is the basic course for Angular.", amt: "$50", dur: & ...

Is there a way to showcase a modal following a timed delay?

I want my modal to appear 2 seconds after the page loads. I've tried setting the state in componentDidUpdate, but I keep getting active: undefined. The active props control the visibility of the modal on the page. When I toggle it to true using the Re ...

Ways to assign a secondary color theme to the DatePicker widget

As someone who is new to exploring Material UI components, I encountered a roadblock while experimenting with different features. <TextField type="email" name="email" id="email" label="Email" variant="outlined" color="secondary" required /> <D ...

Can someone point me to the typescript build option in Visual Studio 2019 Community edition?

When I created a blank node.js web app on VS 2015, there was an option under project properties called "TYPESCRIPT BUILD" that allowed me to configure settings like combining JavaScript output into a single file. After upgrading to VS 2019 Community, I ca ...

Encountering a script error that reads "TypeError: $ is not defined as a function

I am attempting to send an email using web services in asp.net, utilizing html and sending the information through a jquery ajax function. Below is the html form: <div class="col-md-6"> <h2>DROP ME A LINE</h2> & ...

Encountering ExpressionChangedAfterItHasBeenCheckedError during ngOnInit when utilizing Promise

I have a simple goal that I am working on: I want to display data obtained from a service in my component. This is how it used to work: In my component: ... dataSet: String[]; ngOnInit(){ this._service.getDataId().then(data => this.dataSet = da ...

Encountering the message "npm ERR! missing script: start" following the update to .Net 3.0

Previously, the ASP.Net Core 2.2 code (upgraded from 2.1) did not include a start script in package.json. https://github.com/TrilonIO/aspnetcore-angular-universal/blob/master/package.json Upon upgrading to ASP.Net Core 3.0, it now requires a start script ...

Remove any javascript code from the ajax modal when it is closed or hidden

I am in the process of creating a music website that showcases songs along with their lyrics. One of the features I have added is a lyrics button that, when clicked while a song is playing, opens up a modal displaying the live lyrics. Everything works per ...

What is the best way to incorporate a search bar into a dropdown menu?

Would someone be able to assist me in adding a search bar as the primary value of the dropdown menu? I am using ASP.NET MVC and this is my current code snippet. <div class="col-md-8"> <div class="dropdown"> <div class="chzn-d ...

I'm encountering a type error every time I attempt to render an EJS page. Could someone please take a look and help me troubleshoot?

Below is the index.js code: CODE HERE const express = require('express'); const app = express(); const path = require('path'); app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded app.use(ex ...

Utilizing Jquery for Enhanced HTML5 Validation

I need to ensure compatibility with browsers that do not support HTML5 validation. My goal is to display the basic error message from the browser using HTML5, while also adding a CSS class of "error" to each input, label, and parent div for fields with err ...